我想使用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
答案 0 :(得分:0)
只需导入' os'它会起作用:
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)
答案 1 :(得分:0)
我想通了 - 这是因为在.txt文件中,最后一个字符是隐式\n
,因此需要将文件名切片为不包含最后一个字符(变为?
) :
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)