简体   繁体   English

重命名文件,列表中的新名称 - Python

[英]Renaming files, new name from list - Python

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()

I want to rename files based on the list temp_track_titles.我想根据列表 temp_track_titles 重命名文件。 错误

temp_track.titles 的样子

Soundtracks 文件夹的外观

I apologize if confusing.如果造成混淆,我深表歉意。 I have looked around for hours, and could not find a solution.我已经环顾了几个小时,但找不到解决方案。 Basically I want to "map" the names from the temp_tracks_titles list to the files from the folder.基本上我想将 temp_tracks_titles 列表中的名称“映射”到文件夹中的文件。 For example, name #3 from the list should become the name of the file #3 from the folder.例如,列表中的名称 #3 应成为文件夹中文件 #3 的名称。

1.) A while True: loop will repeatedly rename your files for as long as the script is running. 1.) 只要脚本正在运行while True:循环就会反复重命名您的文件。 Are you sure this is what you want to do?确定这是你想做的吗?

2.) You should be iterating through each file in os.listdir() exactly once. 2.) 您应该只遍历os.listdir()中的每个文件一次。 Currently you are iterating the directory for each name that is in temp_track_titles list.目前,您正在为temp_track_titles列表中的每个名称迭代目录。

3.) Each time you remove an actively iterating object, you are skipping to the next iteration directly which messes up your expected order. 3.) 每次remove主动迭代的 object 时,您都会直接跳到下一个迭代,这会打乱您的预期顺序。 Do not remove objects of a collection as you iterate through a collection.不要在遍历集合时删除集合的对象。

Following these comments, you will want to reformat your code thus:根据这些注释,您将需要重新格式化您的代码:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM