如何通过使用 python 将文件名替换为文件夹名称来将文件复制回两个文件夹

How to copy a file two folders back by replacing file name with names of folders using python

我有好几个文件夹,比如a1-b1, a1-b2, a1-b3. a2-b2等等。每个文件夹中都有子文件夹,例如c_1, c_2, c_3 等等。在每个子文件夹中,我都有同名的数据文件,例如abc.dat。我想通过用子文件夹替换其名称来复制 abc.dat 两个文件夹,例如a1-b1-c_1.dat, a1-b1-c_2.dat, a1-b3_c1.dat 等..

我目前的方法只能复制一个文件夹,但也会更改现有目录中 abc.dat 个文件的名称,我现在想避免这种情况,并且希望这些文件在复制时具有所需的更改两个文件夹中的名称,但在其当前目录中以 abc.dat 形式存在。在此先感谢您的支持!

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)

所以,我想出了它的解决方案。在这里!

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)