0

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)
Azhar Khan
  • 3,829
  • 11
  • 26
  • 32
  • `os.listdir` takes a single folder path; you have given two paths. Please refer [documentation](https://docs.python.org/3/library/os.html#os.listdir). – Azhar Khan Dec 02 '22 at 13:40
  • Does this answer your question? [How to move a file in Python?](https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python) – Azhar Khan Dec 02 '22 at 13:40

2 Answers2

1

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

Gameplay
  • 1,142
  • 1
  • 4
  • 16
0

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)
lemon
  • 14,875
  • 6
  • 18
  • 38