简体   繁体   中英

How do I rename several files in folders following the order of a list

I have several folders which contain many files:

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

I also have my_list = [rename1, rename2, rename3, rename4]

I am trying to rename [File1, File2, File3, File4] exactly to follow the order and names of my_list .

I have tried this:

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

but this creates a generator object and contains files which don't match [rename1, rename2, rename3, rename4] as required.

You may use built-in function.

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

You are trying to iterate over two lists.

The following is a fairly standard pattern. Instead of print you would want to use os.rename still to actually rename the files.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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