Python 从文本文件替换目录中的文件名
我想使用Python从包含“目标”名称的.txt文件重命名名为Python 从文本文件替换目录中的文件名,python,file-io,os.path,Python,File Io,Os.path,我想使用Python从包含“目标”名称的.txt文件重命名名为myShow的目录中的文件: 层次结构如下所示: 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, li
myShow
的目录中的文件:
层次结构如下所示:
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
只需导入“操作系统”,它就会工作:
import os
with open('episodes.txt', 'r') as txt:
for dir, subdirs, files in os.walk('myShow'):
for f,line in zip(sorted(files), txt):
if f == '.DS_Store':
continue
originalName = os.path.abspath(os.path.join(dir, f))
newName = os.path.abspath(os.path.join(dir, line + '.m4v'))
os.rename(originalName, newName)
我找到了答案-这是因为在.txt文件中,最后一个字符是隐式的
\n
,因此需要对文件名进行切片,以不包括最后一个字符(它变成了?
):
什么不起作用?尝试在代码中放置一些print语句,或者使用调试器查看f、originalName、newName等的值。到达一个您知道有效的位置(例如将文件放置在同一目录中并测试是否可以重命名它)这是您只需稍微多做一点工作就可以解决的问题。抱歉,忘了补充一点,我已经对它进行了测试,但不明白为什么扩展之前会出现
?
。是因为文本文件在每行末尾都有\n
吗?抱歉,忘了添加我的问题-编辑了问题以产生不正确的输出
import os
with open('episodes.txt', 'r') as txt:
for dir, subdirs, files in os.walk('myShow'):
for f,line in zip(sorted(files), txt):
if f == '.DS_Store':
continue
originalName = os.path.abspath(os.path.join(dir, f))
newName = os.path.abspath(os.path.join(dir, line + '.m4v'))
os.rename(originalName, newName)
import os
def showTitleFormatter(show, numOfSeasons, ext):
for season in range(1, numOfSeasons + 1):
seasonFOLDER = f'S{season}'
targetnames = f'{show}S{season}.txt'
with open(targetnames, 'r') as txt:
for dir, subdirs, files in os.walk(seasonFOLDER):
for f, line in zip(sorted(files), txt):
assert f != '.DS_Store'
originalName = os.path.abspath(os.path.join(dir, f))
newName = os.path.abspath(os.path.join(dir, line[:-1] + ext))
os.rename(originalName, newName)