简体   繁体   中英

Python: Move files from multiple folders in different locations into one folder

I am able to move all files from one folder to another. I need help in order to move files to destination folder from multiple source folders.

import os
import shutil

source1 = "C:\\Users\\user\\OneDrive\\Desktop\\1\\"
source2 = "C:\\Users\\user\\OneDrive\\Desktop\\2\\"
destination = "C:\\Users\\user\\OneDrive\\Desktop\\Destination\\"

files = os.listdir(source1, source2)

for f in files:
    shutil.move(source1 + f,source2 + f, destination + f)

print("Files Transferred")

I am getting error:

files = os.listdir(source1, source2)
TypeError: listdir() takes at most 1 argument (2 given)

This is the line interpreter is complaining about, you cannot pass two directories to os.listdir function

files = os.listdir(source1, source2)

You have to have a nested loop (or list comprehension) to do what you want so:

import os
sources = [source1, source2, ..., sourceN]
files_to_move = []
for source in sources:
    current_source_files =[f"{source}{filename}" for filename in os.listdir(source)]
    files_to_move.extend(current_source_files)
for f in files_to_move:
    shutil.move(f, f"{destination}{f.split(os.sep)[-1]}")

For "cleaner" solution it's worth to look at: https://docs.python.org/3/library/os.path.html#module-os.path

I have found a solution to the problem. I didnt find it on my own unfortunately but as I was finding the answer to this issue I came across this which resolved the problem I was having. The code is as below works just as how I wanted it to work.

import shutil import os

current_folder = os.getcwd()

list_dir = [Folder 1, Folder 2, Folder 3]

content_list = {} for index, val in enumerate(list_dir): path = os.path.join(current_folder, val) content_list[ list_dir[index] ] = os.listdir(path)

merge_folder = #Destination Folder Path

merge_folder_path = os.path.join(current_folder, merge_folder)

for sub_dir in content_list:

for contents in content_list[sub_dir]:

    path_to_content = sub_dir + "/" + contents

    dir_to_move = os.path.join(current_folder, path_to_content )


    shutil.move(dir_to_move, merge_folder_path)

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