sariii
sariii

Reputation: 2150

how to rename with the name of subfolder then copy files in python efficiently

I have a directory in which there is multiple folder inside. name of folder is 1, 2,3,...10. Also there is some files inside these folders. I want to rename the file which the name is topics to the name of subfolder. then copy to the one level before where 1,2,3 folders are there.

For example:

dir1-> 1
         topics
         cd
       2
         topics
         cd
       3
         topics
         cd

I want to rename name of topics to 1 in the first one topics to 2 in the second one topics to 3 in the third one Also copy the newest changed name file into the dir1(one level back where folder 1, 2 ,3 ) are there.

I have tried this:

for root, subdirs, files in os.walk(input_dir):
    for filename in files:
        #print(os.path.join(root, filename))
              if filename=='topics.csv':
                os.rename(os.path.join(root, filename), os.path.join(root, str(i)) + ".csv")
                shutil.move(os.path.join(root,str(i)), os.path.join(input_dir,str(i)))
                i = i+1

But it did not work.

My expected result will be

dir1-> 1
       1.txt
         1.txt
         cd
       2
       2.txt
         2.txt
         cd
       3
       3.txt
         2.txt
         cd

here 1.txt = topics which has been renamed then coppied one level behind Thanks for your help :)

Upvotes: 0

Views: 606

Answers (1)

Angela
Angela

Reputation: 1731

Here is a quick answer. Have not thoroughly tested it, there might be some room for improvement

import os, shutil

input_dir = "/Users/Angela/test"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(input_dir):

for filename in files:
    if filename == 'topics.csv':
        base = os.path.join(os.path.abspath(root))
        #Get current name
        old_name = os.path.join(base, filename)
        #Get parent folder
        parent_folder = os.path.basename(base)
        #New name based on parent folder
        new_file_name = parent_folder + ".csv" #assuming same extension
        new_abs_name = os.path.join(base, new_file_name) 
        #Rename to new name
        os.rename(old_name,new_abs_name)
        #Copy to one level up
        one_level_up = os.path.normpath(os.path.join(base, os.pardir))
        one_level_up_name = os.path.join(one_level_up, new_file_name)
        shutil.copy(new_abs_name,one_level_up_name)

enter image description here

Upvotes: 2

Related Questions