Search code examples
pythonshutil

Copying two source files to one destination in python


You guys were super helpful for my last question so I figured I'd see if you can help me out again. Right now, I have a bunch of folders named P2_## with each of them containing two folders 0_output and 1_output. Inside the each of the output folders I have a file named Bright_Combo.txt. What I want to do is copy the data from both output folders into a Bright_Sum.txt file in the P2_## folder. This is the code I've got so far, but the problem is that it only copies data from the 1_output folder and in one case save an empty copy of the Bright_Sum file into a 0_output folder.

import os
import re
import shutil


def test():
    file_paths = []
    filenames = []
    for root, dirs, files in os.walk("/Users/Bashe/Desktop/121210 p2"):
        for file in files:
            if re.match("Bright_Combo.txt",file):
                file_paths.append(root)
                filenames.append(file)
    return file_paths, filenames

def test2(file_paths, filenames):
    for file_path, filename in zip(file_paths, filenames):
        moving(file_path, filename)

def moving(root,file):
    bcombo = open(os.path.join(root,os.pardir, "Bright_Sum.txt"),'w')
    shutil.copy(os.path.join(root,"Bright_Combo.txt"), os.path.join(root, os.pardir,   "Bright_sum.txt"))

file_paths, filenames = test()
test2(file_paths, filenames)

Thanks for the help everyone =)


Solution

  • Well i cannot give you complete solution, but i can give you an idea...
    This is what i implented for your usecase:

    code:

    import os,re,shutil
    f=[]
    file='Bright_Combo.txt'
    for root,dirs,files in os.walk('/home/ghantasa/test'):
        if file in files:
            f.append(os.path.join(root,file))
    
    for fil in f:
        with open(fil,'r') as readfile:
            data = readfile.readlines()
        with open(os.path.join('/'.join(fil.split('/')[:-2]),'Bright_Sum.txt'),'a') as      writefile:
        writefile.write(''.join(data))  
    

    That worked for me and i hope you can tweak it according to your need.

    Hope this helps .. :)