如果您打印出正在进行的重命名操作,那么就更容易看到发生了什么:
def rename(path):
""" Renames all the files to be cropped-%d.xxx """
count = 0
for thing in os.listdir(path):
root, ext = os.path.splitext(thing)
old = os.path.join(path, thing)
new = os.path.join(path, sys.argv[1] + ".cropped{0}".format(count) + ext)
print("rename from {} to {}".format(old, new))
os.rename(old, new)
count += 1
以下是运行两次的示例输出:
dan@dandesk:~$ python ok.py b
rename from test/4.txt to test/b.cropped0.txt
rename from test/2.txt to test/b.cropped1.txt
rename from test/5.txt to test/b.cropped2.txt
rename from test/7.txt to test/b.cropped3.txt
rename from test/1.txt to test/b.cropped4.txt
rename from test/3.txt to test/b.cropped5.txt
rename from test/6.txt to test/b.cropped6.txt
dan@dandesk:~$ python ok.py b
rename from test/b.cropped3.txt to test/b.cropped0.txt
rename from test/b.cropped4.txt to test/b.cropped1.txt
rename from test/b.cropped2.txt to test/b.cropped2.txt
rename from test/b.cropped5.txt to test/b.cropped3.txt
rename from test/b.cropped1.txt to test/b.cropped4.txt
rename from test/b.cropped0.txt to test/b.cropped5.txt
rename from test/b.cropped6.txt to test/b.cropped6.txt
现在,这里是测试目录的内容:
dan@dandesk:~$ ls -1 test
b.cropped2.txt
b.cropped3.txt
b.cropped4.txt
b.cropped5.txt
b.cropped6.txt
正如您所见,b.cropped1.txt
和b.cropped0.txt
已经消失。上面的输出显示了原因:
rename from test/b.cropped3.txt to test/b.cropped0.txt
rename from test/b.cropped4.txt to test/b.cropped1.txt
...
rename from test/b.cropped1.txt to test/b.cropped4.txt
rename from test/b.cropped0.txt to test/b.cropped5.txt
我们将两个文件重命名为缺失的名称,然后稍后再次重命名它们,这意味着我们会丢失
b.cropped4.txt和
b.cropped5.txt中的任何内容。
您可以通过确保要使用的新名称不存在来避免这种情况,如果存在,则递增计数器
count
,直到找到一个不存在的文件为止:
def rename(path):
""" Renames all the files to be cropped-%d.xxx """
count = 0
for thing in os.listdir(path):
root, ext = os.path.splitext(thing)
old = os.path.join(path, thing)
while True:
new = os.path.join(path, sys.argv[1] + ".cropped{0}".format(count) + ext)
if not os.path.exists(new):
break
count += 1
print("rename from {} to {}".format(old, new))
os.rename(old, new)
count += 1
输出:
dan@dandesk:~$ python ok.py b
rename from test/4.txt to test/b.cropped0.txt
rename from test/2.txt to test/b.cropped1.txt
rename from test/5.txt to test/b.cropped2.txt
rename from test/1.txt to test/b.cropped3.txt
rename from test/3.txt to test/b.cropped4.txt
rename from test/6.txt to test/b.cropped5.txt
dan@dandesk:~$ python ok.py b
rename from test/b.cropped3.txt to test/b.cropped6.txt
rename from test/b.cropped4.txt to test/b.cropped7.txt
rename from test/b.cropped2.txt to test/b.cropped8.txt
rename from test/b.cropped5.txt to test/b.cropped9.txt
rename from test/b.cropped1.txt to test/b.cropped10.txt
rename from test/b.cropped0.txt to test/b.cropped11.txt