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()
添加回答
舉報