2017-12-03 199 views
-1

我想用Python来在从包含“目标”名称的.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) 

但我不硝酸钾w ^为什么我在文件名的扩展月底前获得?

realNameForEpisode1?.m4v 
realNameForEpisode2?.m4v 
realNameForEpisode3?.m4v 
+0

什么没有工作?尝试在代码中放置一些打印语句,或者使用调试器来查看f,originalName,newName等的值。到达一个你知道的地方(比如将一个文件放在同一个目录中,并测试你可以重命名它。)这是你应该能够通过一点点额外的努力来解决你的问题。 – SteveJ

+0

对不起,忘了补充说我已经测试过了,但不明白为什么在扩展前出现'?'。是因为文本文件在每行的末尾有'\ n'吗? –

回答

0

只需导入“操作系统”,它会工作:

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) 
+0

对不起,忘了补充说我有 - 编辑了这个问题产生我的不正确的输出 –

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)