[英]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这是解释器抱怨的行,您不能将两个目录传递给 os.listdir 函数
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对于“更清洁”的解决方案,值得一看: 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导入 shutil 导入 os
current_folder = os.getcwd()当前文件夹 = os.getcwd()
list_dir = [Folder 1, Folder 2, Folder 3] list_dir = [文件夹 1, 文件夹 2, 文件夹 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) 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 = #目标文件夹路径
merge_folder_path = os.path.join(current_folder, merge_folder) merge_folder_path = os.path.join(current_folder, merge_folder)
for sub_dir in content_list:对于 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.