Sim*_*ity 16 python directory rename
我正在尝试使用此Python脚本重命名目录中的多个文件:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(file, str(i)+'.jpg')
i = i+1
Run Code Online (Sandbox Code Playgroud)
当我运行此脚本时,我收到以下错误:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(file, str(i)+'.jpg')
OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
这是为什么?我该如何解决这个问题?
谢谢.
not*_*ess 54
重命名时你没有给出整个路径,这样做:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join([str(index), '.jpg'])))
Run Code Online (Sandbox Code Playgroud)
编辑:感谢tavo,第一个解决方案是将文件移动到当前目录,修复它.
小智 8
import os
from os import path
import shutil
Source_Path = 'E:\Binayak\deep_learning\Datasets\Class_2'
Destination = 'E:\Binayak\deep_learning\Datasets\Class_2_Dest'
#dst_folder = os.mkdir(Destination)
def main():
for count, filename in enumerate(os.listdir(Source_Path)):
dst = "Class_2_" + str(count) + ".jpg"
# rename all the files
os.rename(os.path.join(Source_Path, filename), os.path.join(Destination, dst))
# Driver Code
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
小智 5
您必须先将此路径设为当前工作目录。足够简单。其余代码没有错误。
使其成为当前工作目录:
os.chdir(path)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
47670 次 |
最近记录: |