[英]Trying to rename files with glob and os modules
I'm trying to rename a bunch of files with the glob and os modules, but I'm not getting anywhere. 我正在尝试使用glob和os模块重命名一堆文件,但是我什么也没找到。 I've looked for some solutions but not found any.
我一直在寻找一些解决方案,但没有找到任何解决方案。 "Cannot create a file when that file already exists.".
“该文件已存在时无法创建该文件。”
And if I get that to work, I'm not sure how to rename multiple items, say I have three pictures called img_1001, img_1002, and img_1003. 而且,如果我可以正常工作,则不确定如何重命名多个项目,例如说我有三张图片,分别为img_1001,img_1002和img_1003。 How could I rename these to something like: picture_1, picture_2, and picture_3.
如何将它们重命名为picture_1,picture_2和picture_3。
Here is my code at the moment. 这是我目前的代码。
import os
import glob
x = glob.glob(r"C:\Users\Verzo\Desktop\New folder\*.txt")
for filename in x:
os.rename(filename, "Picture ")
for filename in x:
os.rename(filename, "Picture ")
The script is trying to rename every file in that list to Picture
. 该脚本正在尝试将该列表中的每个文件重命名为
Picture
。 This will not work, as you discovered. 正如您所发现的,这将不起作用。
The following code is untested. 以下代码未经测试。
import os
from glob import glob
for number, filename in enumerate(glob(r"C:\Users\Verzo\Desktop\New folder\*.txt")):
try:
os.rename(filename, "Picture_{0}".format(number))
except OSError as e:
print("Something happened:", e)
Something like that (untested) 那样的东西(未经测试)
import os
import glob
x = glob.glob(r"C:\Users\Verzo\Desktop\New folder\*.txt")
for filename in x:
name, num = filename.split('_')
num = int(num)
os.rename(filename, 'picture_%d' % num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.