简体   繁体   中英

Move files from multiple directories to single directory

I am trying to use the os.walk() module to go through a number of directories and move the contents of each directory into a single "folder" (dir).

In this particular example I have hundreds of .txt files that need to be moved. I tried using shutil.move() and os.rename() , but it did not work.

import os 
import shutil 

current_wkd = os.getcwd()
print(current_wkd)

# make sure that these directories exist

dir_src = current_wkd

dir_dst = '.../Merged/out'

for root, dir, files in os.walk(top=current_wkd):
    for file in files:
        if file.endswith(".txt"):  #match files that match this extension
            print(file)
            #need to move files (1.txt, 2.txt, etc) to 'dir_dst'
            #tried: shutil.move(file, dir_dst) = error

If there is a way to move all the contents of the directories, I would be interested in how to do that as well.

Your help is much appreciated! Thanks.

Here is the file directory and contents

current_wk == ".../Merged 

In current_wk there is:

 Dir1 
 Dir2 
 Dir3..
 combine.py # python script file to be executed 

In each directory there are hundreds of .txt files.

Simple path math is required to find source files and destination files precisely.

import os
import shutil

src_dir = os.getcwd()
dst_dir = src_dir + " COMBINED"

for root, _, files in os.walk(current_cwd):
    for f in files:
        if f.endswith(".txt"):
            full_src_path = os.path.join(src_dir, root, f)
            full_dst_path = os.path.join(dst_dir, f)
            os.rename(full_src_path, full_dst_path)

You have to prepare the complete path of source file, and make sure dir_dst exists.

for root, dir, files in os.walk(top=current_wkd):
    for file in files:
        if file.endswith(".txt"):  #match files that match this extension
            shutil.move(os.path.join(root, file), dir_dst)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM