1 回答

TA贡献1869条经验 获得超4个赞
正如你所建议的,在这里工作得很好。它甚至可以仅过滤文件。glob.pdf
测试后取消注释 3 行。
import os, glob
def convert_multiple(pdf_dir, txt_dir):
if pdf_dir == "": pdf_dir = os.getcwd() # If no pdf_dir passed in
for filepath in glob.iglob(f"{pdf_dir}/**/*.pdf", recursive=True):
text = convert(filepath)
root, _ = os.path.splitext(filepath) # Remove extension
txt_filepath = os.path.join(txt_dir, os.path.relpath(root, pdf_dir)) + ".txt"
txt_filepath = os.path.normpath(txt_filepath) # Not really necessary
print(txt_filepath)
# os.makedirs(os.path.dirname(txt_filepath), exist_ok=True)
# with open(txt_filepath, "wt") as f:
# f.write(text)
pdf_dir = r"C:/Users/Documents/pdf/"
txt_dir = r"C:/Users/Documents/txt/"
convert_multiple(pdf_dir, txt_dir)
若要确定新文件的文件路径,请使用 os.path 模块中的函数。.txt
os.path.relpath(filepath, pdf_dir)返回文件的文件路径,包括与 相关的任何子目录。pdf_dir
假设是:filepath
C:/Users/Documents/pdf/Setec Astronomy/employees.pdf
并且是pdf_dir
C:/Users/Documents/pdf/
它将返回,然后可以将其传递给 ,从而为我们提供了包含额外子目录的完整文件路径。Setec Astronomy/employees.pdfos.path.join()txt_dir
你可以这样做,但你必须确保所有相应的斜杠都在同一个方向上,并且没有额外/缺失的前导/尾随斜杠。txt_filepath = filepath.replace(filepath, pdf_dir)
在打开新文件之前,需要创建任何和所有子目录。 调用以获取文件目录的文件路径,并将其参数设置为 ,以在目录已存在时禁止显示异常。.txtos.path.dirname()os.makedirs()exist_okTrueFileExistsError
打开文件时使用语句以避免显式调用 ,特别是在出现任何异常的情况下。with.txt.close()
添加回答
举报