如何按照列表顺序重命名文件夹中的几个文件

时间:2019-05-04 15:48:56

标签: python file rename

我有几个包含许多文件的文件夹:

Folder
|---Folder1
|      |------File1, File2,...
|
|---Folder2
       |------File3, File4,...

我也有my_list = [rename1, rename2, rename3, rename4]

我正试图按照[File1, File2, File3, File4]的顺序和名称重命名my_list

我已经尝试过了:

list_of_dirs = [path_to_file1, path_to_file2, path_to_file3, path_to_file4]
my_list = [rename1, rename2, rename3, rename4]
for i in list_of_dirs:
    os.rename(i, 'path_to_saving_directory' + str(j for j in my_list))

但这会创建一个生成器对象,并包含与所需的[rename1, rename2, rename3, rename4]不匹配的文件。

2 个答案:

答案 0 :(得分:0)

您可以使用内置功能。<​​/ p>

for i, j in zip(list_of_dirs, my_list):
    os.rename(i, j)

答案 1 :(得分:0)

您正在尝试遍历两个列表。

以下是相当标准的模式。除了打印外,您还想使用os.rename来实际重命名文件。

>>> list_of_paths = ['path1', 'path2', 'path3', 'path4']
>>> new_names = ['rename1', 'rename2', 'rename3', 'rename4']
>>> 
>>> 
>>> for original_path, new_name in zip(list_of_paths, new_names):
...   print(f"need to rename file at {original_path} to {new_name}")
... 
need to rename file at path1 to rename1
need to rename file at path2 to rename2
need to rename file at path3 to rename3
need to rename file at path4 to rename4
>>>