【发布时间】:2019-07-01 15:18:52
【问题描述】:
我尝试编写一些代码来重命名文件夹中的某些文件 - 本质上,它们被列为 xxx_(a).bmp 而它们需要是 xxx_a.bmp,其中 a 从 1 运行到 2000。
我使用内置的 os.rename 函数在循环内交换它们以获得正确的数字,但这给了我FileNotFoundError [WinError2] the system cannot find the file specified Z:/AAA/BBB/xxx_(1).bmp' -> 'Z:/AAA/BBB/xxx_1.bmp'。
如果有人能指出我正确的方向,我已经包含了我在下面编写的代码。我检查了我在正确的目录中工作,它给了我我期望的目录,所以我不确定为什么它找不到文件。
import os
n = 2000
folder = r"Z:/AAA/BBB/"
os.chdir(folder)
saved_path = os.getcwd()
print("CWD is" + saved_path)
for i in range(1,n):
old_file = os.path.join(folder, "xxx_(" + str(i) + ").bmp")
new_file = os.path.join(folder, "xxx_" +str(i)+ ".bmp")
os.rename(old_file, new_file)
print('renamed files')
【问题讨论】:
-
您确定文件名结构正确吗?在较新的 Windows 操作系统上,重复文件的默认命名是
xxx (1).bmp而不是xxx_(1).bmp。空格,不是下划线。
标签: python python-3.x