我不知道哪里出了问题。之前用过rename没问题,其他类似问题找不到解决方法。
import os
import random
directory = "C:\\whatever"
string = ""
alphabet = "abcdefghijklmnopqrstuvwxyz"
listDir = os.listdir(directory)
for item in listDir:
path = os.path.join(directory, item)
for x in random.sample(alphabet, random.randint(5,15)):
string += x
string += path[-4:] #adds file extension
os.rename(path, string)
string= ""
您的代码中有一些奇怪的地方。例如,您的文件源是完整路径,但您要重命名的目标只是一个文件名,因此文件将出现在任何工作目录中——这可能不是您想要的。
您无法避免两个随机生成的文件名相同,因此您可能会以这种方式破坏您的一些数据。
试试这个,它应该可以帮助您找出任何问题。这只会重命名文件,并跳过子目录。
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)
我是一名优秀的程序员,十分优秀!