从文本文件替换目录中的文件名

2024-10-03 11:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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

Tags: 文件pathintxtforosdirline
2条回答

我想出来了-这是因为在.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)

只需导入“操作系统”即可:

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)

相关问题 更多 >