从文本文件中的目录替换文件名
我想用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 
回答:
只需导入“操作系统”,它会工作:
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,所以需要切片文件名,不包括最后一个字符(从而成为一个?):
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) 
以上是 从文本文件中的目录替换文件名 的全部内容, 来源链接: utcz.com/qa/259525.html

