簡體   English   中英

python glob 或 listdir 創建然后將文件從一個目錄保存到另一個

[英]python glob or listdir to create then save files from one directory to another

我正在將文檔從 pdf 轉換為文本。 pdf 目前在一個文件夾中,然后在 txt 轉換后保存到另一個文件夾中。 我有很多這樣的文檔,並且更喜歡遍歷子文件夾並保存到 txt 文件夾中同名的子文件夾,但無法添加該層。

我知道我可以使用 glob 遞歸迭代並對文件列表等執行此操作。但不清楚如何將文件從此文件夾保存到新文件夾。 這不是完全必要的,但會更方便和有效。

有沒有好的方法可以做到這一點?

import os
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert(fname, pages=None):
    if not pages:
        pagenums = set()
    else:
        pagenums = set(pages)

    output = io.StringIO()
    manager = PDFResourceManager()
    converter = TextConverter(manager, output, laparams=LAParams())
    interpreter = PDFPageInterpreter(manager, converter)

    infile = open(fname, 'rb')
    for page in PDFPage.get_pages(infile, pagenums):
        interpreter.process_page(page)
    infile.close()
    converter.close()
    text = output.getvalue()
    output.close
    return text 
    print(text)



def convertMultiple(pdfDir, txtDir):
    if pdfDir == "": pdfDir = os.getcwd() + "\\" #if no pdfDir passed in 
    for pdf in os.listdir(pdfDir): #iterate through pdfs in pdf directory
        fileExtension = pdf.split(".")[-1]
        if fileExtension == "pdf":
            pdfFilename = pdfDir + pdf 
            text = convert(pdfFilename)  
            textFilename = txtDir + pdf.split(".")[0] + ".txt"
            textFile = open(textFilename, "w")  
            textFile.write(text)  


pdfDir = r"C:/Users/Documents/pdf/"
txtDir = r"C:/Users/Documents/txt/"
convertMultiple(pdfDir, txtDir)   

正如你所建議的, 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)   

要確定新.txt文件的文件路徑,請使用os.path模塊中的函數。

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.pdf ,然后可以將其與txt_dir一起傳遞到os.path.join() ,為我們提供包含額外子目錄的完整文件路徑。

你可以做txt_filepath = filepath.replace(filepath, pdf_dir) ,但你必須確保所有相應的斜線都在同一方向,並且沒有額外/缺失的前導/尾隨斜線。

在打開新的.txt文件之前,需要創建任何和所有子目錄。 調用os.path.dirname()以獲取文件目錄的文件路徑,並os.makedirs()並將其exist_ok參數設置為True ,以在目錄已存在時抑制FileExistsError異常。

打開.txt文件時使用with語句以避免顯式調用.close() ,尤其是在出現任何異常的情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM