如何解决在 Python 3.x 中使用 os.walk 和 shutil.move 第一个文件夹消失但文件剩余的问题
我是 Python 新手,我一直在编写一些非常简单的代码。这段代码的工作是创建一个存档文件夹,然后将某个日期之前创建的文件夹移动到存档文件夹中。
例如
当前结构:
ROOT FOLDER:
- Subfolder 1 (old - to move to new archive folder)
- Subfolder 2 (old - to move to new archive folder)
- Subfolder 3 (new)
- Subfolder 4 (new)
提议的新结构 - 将通过以下代码执行:
ROOT FOLDER:
- ARCHIVE (new folder created by code)
--- Subfolder 1 (old - Now a subfolder of the new archive folder)
--- Subfolder 2 (old - Now a subfolder of the new archive folder)
- Subfolder 3 (new)
- Subfolder 4 (new)
这是我的代码:
注意 - 哈希注释只是让我看看代码在哪里 - 当然这里的专家会知道他们在看什么!
# import modules required for this code to work
import os
import shutil
import time
import datetime
from os import path
# ~ from datetime import datetime
# select root working directory:
os.chdir(r'C:/Test Folder')
working_dir = os.getcwd() # current directory path
# function to create list of all subdirectories in current working
# directory
def get_subdirs(dirs):
result = []
for d in dirs:
for subdir in os.listdir(d):
path = os.path.join(d,subdir)
if os.path.isdir(path):
result.append(path)
return result
# Below is a list containing the value assigned to the root folder path
subdirs = [working_dir]
# The number entered as the value of 'levels_down' will tell Python how
# many subfolder levels down it should look
levels_down = 1
for _ in range(levels_down):
subdirs = get_subdirs(subdirs)
# ~ # Folder level above can be tested by uncommenting the following
# line of code: print(*subdirs,sep = "\n")
# Below code gets CREATION date of given folder and converts it to datetime
# format with full date & time
def get_c_time(folder):
c_time = os.path.getctime(folder)
return c_time
# Move all folders (needs to be updated to folders AND files created
# before 'target_date' (as above) to new 'ARCHIVE' folder:
target_date = datetime.datetime(2021,6,3).strftime('%Y-%m-%d')
for root,subfolders,files in os.walk(working_dir):
for subfolder in subfolders:
full_path = os.path.join(root,subfolder)
full_path_c_time = datetime.datetime.fromtimestamp(
get_c_time(full_path)).strftime('%Y-%m-%d')
subpath = os.path.join(root,'ARCHIVE')
if full_path_c_time >= target_date:
source_path = full_path
dest_path = subpath
# print code below shows source & destination are correct
print("source: " + source_path + "\n" +
"destination: " + subpath + "\n")
# shutil.move code below works,but keeps 'dropping' folder #1 of X
shutil.move(source_path,dest_path)
我的问题:
最后一行代码 shutil.move(source_path,dest_path) 有效,但无论我想要移动多少个文件夹,它总是“丢弃”(或删除?)列表中的第一个文件夹。例如。如果我有子文件夹 1 到子文件夹 4,它会将子文件夹 2 > 4 移动到新的 ARCHIVE 文件夹,但子文件夹 1 似乎已经消失在以太中。
如果子文件夹 1 中有文件,这些文件将存放在新的“ARCHIVE”文件夹的根目录中,但子文件夹 1 本身会消失。
我在我的代码末尾(在 os.walk 条目下)尝试了不同的方法,包括将找到的文件夹添加到列表中,然后遍历列表以移动它们,但它做同样的事情。
我在这里搜索了很多次,也将上述内容发布到 r/LearnPython subreddit,但遗憾的是没有收到任何回复。
谁能指出我正确的方向?
提前致谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。