python - 如果文件名是字符串列表的子字符串,则使用父字符串重命名文件
问题描述
我在目录中有文件,文件名是字符串列表的子字符串。我需要用列表中的字符串重命名文件
filenames in "./temp" = aa.txt, bb.txt, cc.txt
list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt']
我希望将文件重命名为list_of_names
. 尝试了下面的代码,但得到一个错误
for filename in os.listdir('./temp'):
for i, item in enumerate(list_of_names):
if filename in item:
os.rename(filename,list_of_names[I])
FileNotFoundError:[Errno 2] 没有这样的文件或目录:'aa.txt' -> 'aa12.txt'
解决方案
尝试:
os.rename(‘./temp/‘ + filename, ‘./temp/‘+ list_of_names[i])
此外,考虑使用 pathlib 进行文件系统操作。
推荐阅读
- elasticsearch - ES - 基于存储桶属性中的值而不是文档值的子存储桶
- unity3d - unity:不同屏幕分辨率下按钮间距不同
- ruby-on-rails - 如何在 Twilio 视频会议中启用录制?
- javascript - 当我更改其中一个时,为什么所有日期选择器值都变为空?
- matlab - 有符号平方根 SSR
- ruby - 验证失败:使用 rspec 上传徽标时,徽标不能为空
- c - 无法在 c 中声明具有变量值的数组
- php - 如何在多个 laravel 分页上实现 AJAX
- python - Pandas 出错:从另一个 python 脚本中读取函数
- kubernetes - GCP 存储桶 gcfuse 和 Kubernetes Engine 权限