gpt4 book ai didi

Python Windows 错误 : [Error 3] The system cannot find the file specified when trying to rename

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:36 25 4
gpt4 key购买 nike

我不知道哪里出了问题。之前用过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)

关于Python Windows 错误 : [Error 3] The system cannot find the file specified when trying to rename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com