这是一个使用Python的
os
和
shutil
库来实现的简单任务。以下是一个实现这个任务的代码示例:
import os
import shutil
def copy_pdfs(source_dir, target_dir):
# 确保目标目录存在,如果不存在则创建
os.makedirs(target_dir, exist_ok=True)
# 遍历源目录树
for item in os.listdir(source_dir):
source = os.path.join(source_dir, item)
target = os.path.join(target_dir, item)
# 如果是.pdf文件,复制到新目录
if item.endswith('.pdf'):
shutil.copy2(source, target) # copy2会保留元数据(例如时间戳)
print(f"复制 {source} 到 {target}")
# 如果是子目录,则递归处理
elif os.path.isdir(source):
copy_pdfs(source, target)
# 使用函数
source_dir = '你的源目录' # 例如 'C:/Users/YourName/Documents'
target_dir = '你的目标目录' # 例如 'C:/Users/YourName/Documents/PDFs'
copy_pdfs(source_dir, target_dir)
请将
'你的源目录'
和
'你的目标目录'
替换为实际的路径。这个脚本会遍历源目录及其子目录,找到所有以
.pdf
结尾的文件,并将它们复制到目标目录中。如果目标目录不存在,脚本会创建它。
shutil.copy2
用于保持文件的元数据(如时间戳)。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70033603/viewspace-2981397/ ,如需转载,请注明出处,否则将追究法律责任。