Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two folders in python

Tags:

python

merge

I need to merge two folders,

The folders are named 12345 and 12345_

How would I merge the two?

I have tried but I end up with '12345.'

for file in files:
    subFolder = os.path.join(destpath, file[:6])
    if not os.path.isdir(subFolder):
        os.makedirs(subFolder)
    shutil.copy(os.path.join(root, file), subFolder)
like image 864
lithocrat Avatar asked Mar 06 '18 02:03

lithocrat


People also ask

How do I merge two folders together?

If you are just looking to merge the contents of two directories into a single folder, then the default method is the best approach. Just open File Explorer, rename one of the folders to the same name, and copy-paste over the other, letting Windows handle the merger.

How do I make multiple folders in Python?

Declare the root directory where we want to create the list of folders in a variable. Initialize a list of items. Then iterate through each element in the list. The os module makes a folder of each element of the list in the directory where our python ide is installed.

How do I merge all TXT files into a directory in Python?

use "cat *. txt > all.


2 Answers

You could use something like this, which copies all the files from folder one to folder two so folder two will have all files from one and two:

#!/usr/bin/env python

import subprocess as sbp
import os

path=raw_input('Please enter a path\n')
fol = os.listdir(path)
p2 = raw_input('Please enter a path\n')

for i in fol:
    p1 = os.path.join(path,i)
    p3 = 'cp -r ' + p1 +' ' + p2+'/.'
    sbp.Popen(p3,shell=True)
like image 170
Omi Harjani Avatar answered Oct 02 '22 16:10

Omi Harjani


From python, you could also call rsync, which is made for this.

import subprocess

## define your paths
path1 = '/path/to/12345/'
path2 = '/path/to/12345_/'

## where to place the merged data
merged_path = '/path/to/merged/'

## write an rsync commands to merge the directories
rsync_cmd = 'rsync' + ' -avzh ' + path1 + ' ' + path2 + ' ' + merged_path

## run the rsync command
subprocess.run(rsync_cmd, shell=True)

like image 38
Alex Witsil Avatar answered Oct 02 '22 14:10

Alex Witsil