首页 > 解决方案 > Python os.rename() 多个文件导致除最后一个文件外的所有文件丢失

问题描述

下面的代码运行没有任何错误或警告。它需要一个从旧文件名到新文件名的列表,并将其放入以旧文件名为键的字典中。然后它将给定路径的所有文件名读入列表。然后它遍历每个文件名的列表并在字典中查找命中。如果找到命中,则文件名 (path+name) 将重命名为 (path+val)。

该路径包含 361 个文件,其中包括隐藏的 .DS_Store 文件。该代码过滤掉隐藏文件,留下我希望重命名的 360 文件名。所有感兴趣的文件都以“0”到“9”开头。所有 360 文件名都可以在字典中找到。

执行后,路径中只剩下一个文件。它是 360 文件中的最后一个,并且已重命名。其他 359 个文件消失了。为什么?他们去哪儿了?我错过了什么?

我看到了几篇与 os.rename 相关的帖子,但没有一个回答这个问题。

谢谢丹

import os

# File name positions: OLD 0 to 113  NEW 115 to end of line
new_list = open("/Users/testfolder/new_list.txt", "r")

# Define a file dictionary
file_dict = {}

# Load contents of new_list into the file dictionary.
# KEY=old file name, VAL=New file name
for line in new_list:
    (key, val) = line[0:114].strip(), line[115:].strip()
    file_dict[key] = val

#print(file_dict)

# Path where files reside
path='/Users/testfolder/files/'

# Define a list of files in the path
files = []
file_path_count=0
file_to_rename_count=0
files_renamed=0
for name in os.listdir(path):
    file_path_count +=1
    print('name: ',name)
    # If valid path/file that begins with number 0 thru 9
    # .DS_Store file will be omitted from rename logic
    if os.path.isfile(os.path.join(path, name)) and name[0] in ('1','2','3','4','5','6','7','8','9','0'):
        files.append(name.strip())
        file_to_rename_count +=1
        #print('file to rename: ', name)
        # If the file name in path is found in the file_dict, key=name
        if file_dict.get(name.strip(),'Not Found') == 'Not Found':
            print('not found in file_dict')
        else:
            # File found in file_dict. Rename old file name to new file name
            print('***** renaming: ', path+name, ' to: ', path+file_dict.get(name))
            os.rename(path+name, path+val)
            files_renamed +=1

files.sort()
print('files in the path to rename: ',files)  
print('Number of files found in path: ',file_path_count)  # Count includes .DS_Store file

# The following two counts match and are one less than file_path_count as expected
print('Number of files to rename: ',file_to_rename_count) # Count excluding .DS_Store
print('Number of files renamed: ',files_renamed) # Count Excluding .DS_Store

# After running this program, all but the last file in "path" are missing.  Why, and where did they go?

标签: python

解决方案


val永远不会重新分配,它将保留它在第一次使用的循环结束时所具有的任何值。–万萨

为了扩展 vanza 的评论,这里有一个简单的例子来说明正在发生的事情。

old_names = ['murder', 'arson', 'jaywalking']
new_names = ['spam', 'eggs', 'baked beans']

# This is analagous to your first for loop...
for new_name in new_names:
    val = new_name

# We're now done assigning to val, so for the rest of the program,
# val == 'baked beans'

# This is analagous to your second for loop...
for index in range(len(old_names)):
    # Every single time we replace an item in the list, val is still the
    # same.
    old_names[index] = val

print(old_names)
# Output: ['baked beans', 'baked beans', 'baked beans']

所以你所做的是你已经浏览了你所有的文件,并将它们中的每一个重命名为相同的名称。这意味着第二个将覆盖第一个,第三个将覆盖第二个,依此类推,直到您剩下的就是您重命名的最终文件。


另一方面,可以使用pathlibos完成的许多文件/文件夹操作通常更干净、更方便。我建议你去看看,它非常棒。


推荐阅读