1

I have several folders such as a1-b1, a1-b2, a1-b3. a2-b2 and so on. Within each folder there are subfolders e.g. c_1, c_2, c_3 and so on. Within each subfolder I have data files with same name e.g. abc.dat. I desire to copy abc.dat two folders back by replacing its name with subfolders e.g. a1-b1-c_1.dat, a1-b1-c_2.dat, a1-b3_c1.dat etc..

My present approach can only copy one folder back, but also changes the name of abc.dat files in their existing directories, which I would now like to avoid and prefer that these files are copied with their desired changed names in two folders back, but exist as abc.dat in their current directories. Thanks in advance for your support!

input_dir = "/user/my_data"
# 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 == 'abc.dat':
            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 + ".dat" #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)
ali
  • 61
  • 2
  • 9

1 Answers1

1

So, I figured out its solution. Here it is!

import os
import shutil
current_dir = os.getcwd()
for dirpath, dirs, files in os.walk(current_dir):
    for f in files:
        if f.endswith('.dat'):
            folder_1 = os.path.split(os.path.split(dirpath)[0])[1]
            folder_2 = os.path.split(os.path.split(dirpath)[1])[1]
            os.rename(os.path.join(dirpath, f), 
                      os.path.join(dirpath, folder_1 + '-' + folder_2 + '.dat')) 
            totalCopyPath = os.path.join(dirpath, folder_1 + '-' + folder_2 + '.dat') 
            shutil.copy(totalCopyPath,current_dir)
ali
  • 61
  • 2
  • 9