gpt4 book ai didi

python - 将文件夹中的文件移动到顶级目录

转载 作者:行者123 更新时间:2023-12-04 17:25:14 25 4
gpt4 key购买 nike

我正在尝试为我的工作完成一个脚本,以清理他们的文件组织系统。我的脚本的最后一部分需要进入给定目录中的所有文件夹,并将每个文件夹中的所有文件移动到该目录中。例如:

import os
path = 'C:/User/Tom/Documents'
folders = os.listdir(path)
print(folders)

假设文件夹结构是这样的:
Documents  
[________ Folder A
..................[_________ File 1
..................[_________ File 2
[________ Folder B
..................[_________ File 3
..................[_________ File 4
[________ Folder C
..................[_________ File 5
..................[_________ File 6
..................[_________ File 7

我的目标是以某种方式进入“文档”下的每个文件夹,通过将所有文件向上移动一级来清空文件夹,而无需输入文件夹名称或文件名以位于如下所示的文档路径中:
Documents  
[________ Folder A
[_________ File 1
[_________ File 2
[________ Folder B
[_________ File 3
[_________ File 4
[________ Folder C
[_________ File 5
[_________ File 6
[_________ File 7

我对 python 比较陌生,我唯一想知道如何有效地做到这一点,那就是输入大量进入每个文件夹目录的代码,然后shutil.move() 它们。但是,这对我的应用程序不起作用,因为脚本需要能够为 X 数量的文件夹和 Y 数量的文件完成此任务,而不必输入每个文件夹路径。

我正在寻求有关循环遍历“文件夹”列表的有效方法的任何建议,只需将文件从文件夹中移到路径的目录中即可。
抱歉,帖子太长了,我只是想尽可能详细地说明我的问题,谢谢!

最佳答案

我会推荐使用 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

这会将所有内容移动到顶级目录。

关于python - 将文件夹中的文件移动到顶级目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com