Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one rename multiple files within folders using python?

I have over 1000 folders in 'my documents'. In each folder there are only 4 photos that need to be named to 'North' 'East' 'South' and 'West' in that order. Currently they are named DSC_XXXX. I have written this script but it is not executing.

import sys, os

folder_list = []
old_file_list = []
newnames = [North, South, East, West]

for file in os.listdir(sys.argv[1]):
    folder_list.append(file)

 for i in range(len(folder_list)):
    file = open(folder_list[i], r+)
    for file in os.listdir(sys.argv[1] + '/' folder_list[i]):
       old_file_list.append(file)
       os.rename(old_file_list, newnames[i])

My method of thinking was to get all the names of the 1000 folders and store them in folder_list. Then open each folder and save the 4 picture names in old_file_list. From there I would like to use the os.rename(old_file_list, newnames[i]) to rename the 4 photos to North East South and West. Then I want this to loop for as many folders that are in 'my documents'. I am new to python and any help or suggestions would be greatly appreciated.

like image 971
ErrorMaster Avatar asked Jun 24 '26 15:06

ErrorMaster


1 Answers

You don't need all the lists, just rename all files on the fly.

import sys, os, glob

newnames = ["North", "South", "East", "West"]

for folder_name in glob.glob(sys.argv[1]):
    for new_name, old_name in zip(newnames, sorted(os.listdir(folder_name))):
       os.rename(os.path.join(folder_name, old_name), os.path.join(folder_name, new_name))
like image 104
Daniel Avatar answered Jun 26 '26 05:06

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!