skip to content
Liu Yang's Blog

脚本:批量移动子目录中的 PDF

/ 2 min read

Updated:

下载的论文、资料常常散落在一堆子文件夹里。这个脚本会遍历当前目录下的每个子文件夹,把其中的 PDF 文件移动到 ./dest,并用 tqdm 显示进度。

只处理一层子文件夹,不会继续往下递归;目标目录中如果有同名文件,会被覆盖。

"""
file: extract_files.py
author: linu
date: 2024-10-11
description: 从当前目录下的各个文件夹中抽取所有 PDF 文件,放入目标目录。
"""
import os
import shutil
from tqdm import tqdm
source_dir = "./"
dest_dir = "./dest"
# 判断目标目录是否存在,不存在则创建
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
# 待处理的子目录:是目录,且不是目标目录
folder_list = [
_
for _ in os.listdir(source_dir)
if os.path.isdir(_) and not os.path.samefile(_, dest_dir)
]
filepath_list = []
for folder in folder_list:
# 子目录中的文件
file_list = [
_
for _ in os.listdir(os.path.join(source_dir, folder))
if os.path.isfile(os.path.join(source_dir, folder, _))
]
# 只保留 PDF
for file in file_list:
if file.endswith(".pdf"):
filepath_list.append((os.path.join(source_dir, folder, file), file))
loop = tqdm(filepath_list)
# 移入目标目录
for filepath, filename in loop:
shutil.move(filepath, os.path.join(dest_dir, filename))
loop.set_postfix({"file": filename})
loop.close()
print("Done!")

整理时把“创建目标目录”挪到了遍历之前。原脚本先调用 os.path.samefile(_, dest_dir),如果 ./dest 还不存在就会直接报错。