[英]Copy pdfs in a directory to folders with the same name as the PDFs
我想将目录中的pdf文件放入同名文件夹中。 那些具有相同名称的文件夹已经创建,并且与我想要移入的 pdf 文件位于同一目录中。
我在 python 方面相对较新,在代码上还没有走得很远。 目前,当我运行下面的程序时,它只打印 .pdf 文件,但不打印目录中的子文件夹(除此之外,我不确定为什么在下面的代码中看不到目录中的子文件夹。)
import os
from shutil import copyfile
path_to_files = "C:\\tmp\\all_files_converted\\"
def copy_documents(file_path):
for f in os.listdir(file_path):
print(f)
copy_documents(path_to_files)
你可以使用shutil.move(src, dst)
import shutil
shutil.move(src, dst)
import os
from shutil import copyfile
from glob import glob
path_to_files = "pasta"
def copy_documents(path_to_files):
# os.path is a module to work with file paths
# Using the module glob to list all pdf files of a folder
for file_path in glob(os.path.join(path_to_files, "*.pdf")):
# basename will return the filename without the rest of the path ie: "something.pdf"
pdf_file_name = os.path.basename(file_path)
dest_folder = os.path.join(path_to_files, pdf_file_name[:-4])
print(f"Copy {file_path} to {dest_folder}")
copyfile(file_path, os.path.join(dest_folder, pdf_file_name))
copy_documents(path_to_files)
我建议阅读https://docs.python.org/3/library/os.path.html和https://docs.python.org/3/library/glob.html
了解更多信息。
您可以使用pathlib
和shutil
来执行此操作:
from pathlib import Path
from shutil import move
path_to_files = Path(r"C:\tmp\all_files_converted")
for pdf_path in path_to_files.glob("*.pdf"):
dir_path = path_to_files / pdf_path.stem
dir_path.mkdir()
move(pdf_path, dir_path / pdf_path.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.