我不知道怎么了.我以前使用过重命名没有任何问题,也无法在其他类似问题中找到解决方案.import osimport randomdirectory = C:\\whateverstring = alphabet = abcdefghijklmnopqrstuvwxyzlistDir = os.listd...

我不知道怎么了.我以前使用过重命名没有任何问题,也无法在其他类似问题中找到解决方案.
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 WindowsError:[错误3]尝试重命名时系统找不到指定的文件


基础教程推荐
猜你喜欢
- Python实现发送警告通知到企业微信方法详解 2023-08-11
- Python画图时如何调用本地字体 2023-08-04
- 在Windows Server 2012上如何处理“ OverflowError:Python int太大而无法转换为C long”错误,如何获得转换? 2023-11-11
- Python线程编程之Thread详解 2023-08-04
- 使用nohup ps aux grep kill启动/停止后台Python进程 2023-11-13
- Windows环境下Python2(或2.7版本)命令行tab自动补全设置 2023-09-03
- centos7 安装python3 2023-09-04
- Python中re模块:匹配开头/结尾(^/$) 2022-09-02
- pandas round方法保留两位小数的设置实现 2022-08-30
- Python之多进程(multiprocessing)学习:创建进程,join方法 2023-11-13