我想使用Python从包含“target”名称的.txt文件重命名名为myShow
的目录中的文件:
realNameForEpisode1
realNameForEpisode2
realNameForEpisode3
层次结构如下所示:
episodetitles.txt
myShow
├── ep1.m4v
├── ep2.m4v
└── ep3.m4v
我尝试了以下方法:
import os
with open('episodetitles.txt', 'r') as txt:
for dir, subdirs, files in os.walk('myShow'):
for f, line in zip(sorted(files), txt):
originalName = os.path.abspath(os.path.join(dir, f))
newName = os.path.abspath(os.path.join(dir, line + '.m4v'))
os.rename(originalName, newName)
但我不知道为什么在扩展名之前的文件名末尾有一个?
:
realNameForEpisode1?.m4v
realNameForEpisode2?.m4v
realNameForEpisode3?.m4v
我想出来了-这是因为在.txt文件中,最后一个字符是一个隐式的
\n
,所以需要对文件名进行切片以不包含最后一个字符(它变成了?
):只需导入“操作系统”即可:
相关问题 更多 >
编程相关推荐