使用 Python 重命名目录中的多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37467561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Renaming multiple files in a directory using Python
提问by Simplicity
I'm trying to rename multiple files in a directory using this Python script:
我正在尝试使用此 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
When I run this script, I get the following error:
当我运行此脚本时,出现以下错误:
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
Why is that? How can I solve this issue?
这是为什么?我该如何解决这个问题?
Thanks.
谢谢。
回答by noteness
You are not giving the whole path while renaming, do it like this:
重命名时您没有提供整个路径,请这样做:
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'])))
Edit: Thanks to tavo, The first solution would move the file to the current directory, fixed that.
编辑:感谢 tavo,第一个解决方案将文件移动到当前目录,修复了这个问题。
回答by Abid413119
You have to make this path as a current working directory first. simple enough. rest of the code has no errors.
您必须先将此路径设为当前工作目录。足够简单。其余代码没有错误。
to make it current working directory:
使其成为当前工作目录:
os.chdir(path)
回答by jayesh
As per @daniel's comment, os.listdir() returns just the filenames and not the full path of the file. Use os.path.join(path, file) to get the full path and rename that.
根据@daniel 的评论, os.listdir() 仅返回文件名而不是文件的完整路径。使用 os.path.join(path, file) 获取完整路径并重命名。
import os
path = 'C:\Users\Admin\Desktop\Jayesh'
files = os.listdir(path)
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, 'xyz_' + file + '.csv'))
回答by Binayak
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()
回答by Sri Ganesh Tallapaneni
If your files are renaming in random manner then you have to sort the files in the directory first. The given code first sort then rename the files.
如果您的文件以随机方式重命名,那么您必须首先对目录中的文件进行排序。给定的代码首先排序然后重命名文件。
import os
import re
path = 'target_folder_directory'
files = os.listdir(path)
files.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])
for i, file in enumerate(files):
os.rename(path + file, path + "{}".format(i)+".jpg")
回答by sivi
Just playing with the accepted answer define the path variable and list:
只是玩接受的答案定义路径变量和列表:
path = "/Your/path/to/folder/"
files = os.listdir(path)
and then loop over that list:
然后遍历该列表:
for index, file in enumerate(files):
#print (file)
os.rename(path+file, path +'file_' + str(index)+ '.jpg')
or loop over same way with one line as python list comprehension :
或以与 python list comprehension 相同的方式循环一行:
[os.rename(path+file, path +'jog_' + str(index)+ '.jpg') for index, file in enumerate(files)]
I think the first is more readable, in the second the first part of the loop is just the second part of the list comprehension
我认为第一个更具可读性,第二个循环的第一部分只是列表理解的第二部分
回答by aljgom
I worked on a quick and flexible script to take care of displaying differences, asking for confirmations, and renaming. If you need a working solution, you can copy this script and place it in the folder of which you want to rename files. https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8
我编写了一个快速灵活的脚本来处理显示差异、请求确认和重命名。如果您需要一个有效的解决方案,您可以复制此脚本并将其放在要重命名文件的文件夹中。 https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8
It renames files in current directory by passing "rename functions", each function can take care of a change. Then determines the changes that each function will make and displays the differences using colors, and asks for confirmation to perform the changes. Works on pycharm, haven't tested it in different consoles
它通过传递“重命名函数”来重命名当前目录中的文件,每个函数都可以处理更改。然后确定每个功能将进行的更改并使用颜色显示差异,并要求确认执行更改。适用于 pycharm,尚未在不同控制台中测试过