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

Jac*_*nce 3 python parsing naming for-loop pypdf

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

Gee*_*ode 5

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

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()
Run Code Online (Sandbox Code Playgroud)