'Create CSV file to store old folder name and new folder name

I have python code to rename multiple folder name and create new folder name , but I don't know how to create CSV file and store the old folder name and new folder name to track the details example : Old folder name --> python1122 renamed the folder name to --> python3344

I want to store this details into csv file like

Old_folder_name | New_folder_name
python1122      | python3344

Could you please help me with this?

My code to rename folder name:

Import os


for filename in os.listdir(Folder):
    
    os.rename(Folder+'/'+filename, Folder + '/' + 'python3344')
    print (filename)


Solution 1:[1]

You can use csv.DictWriter https://docs.python.org/3/library/csv.html#csv.DictWriter

Assuming you stores the mapping of filenames in d_folder_name dict

with open('names.csv', 'w') as csvfile:
    fieldnames = ['Old_folder_name', 'New_folder_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for k, v in d_folder_name.items():
      writer.writerow({'Old_folder_name': k, 'New_folder_name': v})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sirakiin