我不明白出了什么问题。我以前使用过重命名没有任何问题,并且在其他类似问题中找不到解决方案。
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)