skip to content
Liu Yang's Blog

[Script] Move PDF Files from Subdirectories to a Destination Folder

/ 1 min read

"""
file: extract_files.py
author: linu
date: 2024-10-11
description: 用于从当前目录中的文件夹中抽取所有文件, 并放入目标目录中.
"""
import os
import shutil
from tqdm import tqdm
source_dir = "./"
dest_dir = "./dest"
# 将操作目录放入列表
folder_list = [
_
for _ in os.listdir(source_dir)
if os.path.isdir(_) and not os.path.samefile(_, dest_dir) # 是目录,且不是目标目录
]
# 判断目标目录是否存在,并创建
if not os.path.exists(dest_dir):
os.mkdir(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, _)) # 必须是文件
]
# 获得符合条件的文件
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": f"{filename}"})
loop.close()
print("Done!")