【问题标题】:Renaming files, new name from list - Python重命名文件,列表中的新名称 - Python
【发布时间】:2020-09-23 16:30:30
【问题描述】:
def thing():
    os.chdir("D:\Desktop\SoundTracks")
    root = "D:\Desktop\SoundTracks"
    temp_track_titles = []
    for f in os.listdir():
        temp_track = TinyTag.get(root + "\\" + f)
        temp_track_titles.append(temp_track.title)
        #print(temp_track.title)
        #new_name = '{}-{}{}'.format(temp_track.title,temp_track.album,f_ext)
        #os.rename(f,new_name)
    temp_track_titles = [''.join(c for c in s if c not in string.punctuation) for s in temp_track_titles]
    #print(temp_track_titles)
    for i in temp_track_titles:
        for f in os.listdir():
            new_name = '{}{}'.format(i,'.mp3')
            os.rename(f,new_name)
            temp_track_titles.remove(i)

while True:
    thing()

我想根据列表 temp_track_titles 重命名文件。

如有混淆,我深表歉意。我已经环顾了几个小时,但找不到解决方案。基本上我想将 temp_tracks_titles 列表中的名称“映射”到文件夹中的文件。例如,列表中的名称 #3 应成为文件夹中文件 #3 的名称。

【问题讨论】:

  • 为什么不在你注释掉的第一个循环中直接重命名?

标签: python file rename file-rename


【解决方案1】:

1.) 只要脚本正在运行,while True: 循环就会反复重命名您的文件。你确定这是你想做的吗?

2.) 您应该只对os.listdir() 中的每个文件进行一次迭代。目前,您正在为 temp_track_titles 列表中的每个名称迭代目录。

3.) 每次您remove 一个积极迭代的对象时,您都会直接跳到下一次迭代,这会打乱您的预期顺序。不要在遍历集合时删除集合的对象。

按照这些 cmets,您将需要重新格式化您的代码:

def thing():
    root = "D:\Desktop\SoundTracks"
    os.chdir(root)
    for f in os.listdir():
        temp_track = ''.join(c for c in TinyTag.get(root + "\\" + f) if c not in string.punctuation)
        new_name = '{}.mp3'.format(temp_track)
        os.rename(f, new_name)

thing()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 2015-10-23
    • 1970-01-01
    • 2011-10-02
    • 2015-11-28
    • 1970-01-01
    • 2021-10-26
    • 2020-12-03
    相关资源
    最近更新 更多