你的代码中有一些奇怪的东西。例如,您的文件源是完整路径,但您重命名的目标只是一个文件名,因此文件将出现在工作目录中 - 这可能不是您想要的。
您无法保护两个随机生成的文件名相同,因此您可以通过这种方式销毁某些数据。
试试这个,这可以帮助您找出任何问题。这只会重命名文件,并跳过子目录。
import os
import random
import string
directory = "C:\\whatever"
alphabet = string.ascii_lowercase
for item in os.listdir(directory):
old_fn = os.path.join(directory, item)
new_fn = ''.join(random.sample(alphabet, random.randint(5,15)))
new_fn += os.path.splitext(old_fn)[1] #adds file extension
if os.path.isfile(old_fn) and not os.path.exists(new_fn):
os.rename(path, os.path.join(directory, new_fn))
else:
print 'error renaming {} -> {}'.format(old_fn, new_fn)