Skip to main content
 首页 » 编程设计

python之将所有PDF文件转换为目录中的文本

2025年05月04日7mate10pro

我刚下载 PDFMiner将 PDF 文件转换为文本。我通过在我的终端上执行这个命令来转换文件

python pdf2txt.py -o myOutput.txt simple1.pdf 

它运行良好,现在我想将该函数嵌入到我的简单 Python 脚本中。我想转换目录中的所有 PDF 文件

# Lets say I have an array with filenames on it 
files = [ 
    'file1.pdf', 'file2.pdf', 'file3.pdf' 
] 
 
# And convert all PDF files to text 
# By repeatedly executing pdf2txt.py 
for x in range(0, len(files)) 
    # And run something like 
    python pdf2txt.py -o output.txt files[x] 

我也尝试过使用 os.system 但出现了一个闪烁的窗口(我的终端)。我只是想将阵列中的所有文件转换为文本。

请您参考如下方法:

使用 subprocess 模块。

import subprocess 
 
files = [ 
    'file1.pdf', 'file2.pdf', 'file3.pdf' 
] 
for f in files: 
    cmd = 'python pdf2txt.py -o %s.txt %s' % (f.split('.')[0], f) 
    run = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    out, err = run.communicate() 
 
    # display errors if they occur     
    if err: 
        print err 

阅读subprocess documentation获取更多信息。