如何将我的 python 代码一次应用于文件夹中的所有文件,以及如何为每个后续输出文件创建一个新名称?

How do I apply my python code to all of the files in a folder at once, and how do I create a new name for each subsequent output file?

我正在使用的代码接收一个 .pdf 文件,并输出一个 .txt 文件。我的问题是,如何创建一个循环(可能是一个 for 循环),它对以“.pdf”结尾的文件夹中的所有文件一遍又一遍地运行代码?此外,如何在每次循环运行时更改输出,以便每次都可以写入一个与输入文件同名的新文件(即 1_pet.pdf > 1_pet.txt、2_pet.pdf > 2_pet.txt, 等等)

目前的代码如下:

path="2_pet.pdf"
content = getPDFContent(path)
encoded = content.encode("utf-8")
text_file = open("Output.txt", "w")
text_file.write(encoded)
text_file.close()

对目录中的所有 PDF 文件进行操作的一种方法是调用 glob.glob() 并迭代结果:

import glob
for path in glob.glob('*.pdf')
    content = getPDFContent(path)
    encoded = content.encode("utf-8")
    text_file = open("Output.txt", "w")
    text_file.write(encoded)
    text_file.close()

另一种方法是允许用户指定文件:

import sys
for path in sys.argv[1:]:
    ...

然后用户像python foo.py *.pdf一样运行你的脚本。

创建一个函数来封装您要对每个文件执行的操作。

import os.path

def parse_pdf(filename):
    "Parse a pdf into text"
    content = getPDFContent(filename)
    encoded = content.encode("utf-8")
    ## split of the pdf extension to add .txt instead.
    (root, _) = os.path.splitext(filename)
    text_file = open(root + ".txt", "w")
    text_file.write(encoded)
    text_file.close()

然后将此函数应用于文件名列表,如下所示:

for f in files:
    parse_pdf(f)

您可以使用递归函数在文件夹和所有子文件夹中搜索以 pdf 结尾的文件。然后获取这些文件,然后为其创建一个文本文件。

可能是这样的:

import os

def convert_PDF(path, func):
    d = os.path.basename(path)
    if os.path.isdir(path):
        [convert_PDF(os.path.join(path,x), func) for x in os.listdir(path)]
    elif d[-4:] == '.pdf':
        funct(path)

# based entirely on your example code
def convert_to_txt(path):
    content = getPDFContent(path)
    encoded = content.encode("utf-8")
    file_path = os.path.dirname(path)
    # replace pdf with txt extension
    file_name = os.path.basename(path)[:-4]+'.txt'
    text_file = open(file_path +'/'+file_name, "w")
    text_file.write(encoded)
    text_file.close()

convert_PDF('path/to/files', convert_to_txt)

因为实际操作是可变的,你可以用你需要执行的任何操作替换函数(比如使用不同的库,转换为不同的类型等)

以下脚本解决了您的问题:

import os

sourcedir = 'pdfdir'

dl = os.listdir('pdfdir')

for f in dl:
    fs = f.split(".")
    if fs[1] == "pdf":
        path_in = os.path.join(dl,f)
        content = getPDFContent(path_in)
        encoded = content.encode("utf-8")
        path_out = os.path.join(dl,fs[0] + ".txt")
        text_file = open(path_out, 'w')
        text_file.write(encoded)
        text_file.close()