[英]Move files in folders to a top-level directory
I am trying to complete a script for my work that cleans up their file organization system. 我正在尝试为我的工作完成一个清理文件组织系统的脚本。 The last part of my script needs to go inside all folders in a given directory, and move all files in every folder to the directory.
我的脚本的最后一部分需要进入给定目录中的所有文件夹,并将每个文件夹中的所有文件移动到目录中。 For example:
例如:
import os
path = 'C:/User/Tom/Documents'
folders = os.listdir(path)
print(folders)
Lets say the folder structure is like this: 让我们说文件夹结构是这样的:
Documents
[________ Folder A
..................[_________ File 1
..................[_________ File 2
[________ Folder B
..................[_________ File 3
..................[_________ File 4
[________ Folder C
..................[_________ File 5
..................[_________ File 6
..................[_________ File 7
My goal is to somehow go into each folder under "Documents", empty out the folders by moving all of the files one level up without having to input folder names or file names to be in the Documents path that looks like this: 我的目标是以某种方式进入“文档”下的每个文件夹,通过将所有文件移动一级来清空文件夹,而无需在文档路径中输入文件夹名称或文件名,如下所示:
Documents
[________ Folder A
[_________ File 1
[_________ File 2
[________ Folder B
[_________ File 3
[_________ File 4
[________ Folder C
[_________ File 5
[_________ File 6
[_________ File 7
I am newer to python and my only thought on how to efficiently do this would be to type out a lot of code that goes into each folder directory, and shutil.move() them. 我是python的新手,我对如何有效地做到这一点的唯一想法是输入进入每个文件夹目录的很多代码,以及shutil.move()它们。 However this wouldn't work for my application as the script needs to be able to complete this task for X amount of folders with Y amount of files and not having to input each folder path.
但是这对我的应用程序不起作用,因为脚本需要能够使用Y量的文件完成此X任务文件夹的任务,而不必输入每个文件夹路径。
I am asking for any advice on an efficient way I can loop through my 'folders' list and simply move the files out of the folder into the path's directory. 我要求以有效的方式提出任何建议,我可以遍历我的“文件夹”列表,只需将文件从文件夹中移出到路径的目录中即可。
Sorry for the long post, I just wanted to be as detailed as possible about my question, thanks! 对不起,很长的帖子,我只想尽可能详细地说明我的问题,谢谢!
I would recommend a recursive bottom-up traversal using os.walk
, and moving your files accordingly. 我建议使用
os.walk
进行递归的自下而上遍历,并相应地移动文件。
import os
import shutil
doc_path = 'C:/User/Tom/Documents'
for root, dirs, files in os.walk(doc_path, topdown=False):
for file in files:
try:
shutil.move(os.path.join(root, file), doc_path)
except OSError:
pass
This will move everything to the top level directory. 这会将所有内容移动到顶级目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.