如何将我的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等)
The code I am working with takes in a .pdf file, and outputs a .txt file. My question is, how do I create a loop (probably a for loop) which runs the code over and over again on all files in a folder which end in ".pdf"? Furthermore, how do I change the output each time the loop runs so that I can write a new file each time, that has the same name as the input file (ie. 1_pet.pdf > 1_pet.txt, 2_pet.pdf > 2_pet.txt, etc.)
这是到目前为止的代码:
Here is the code so far:
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()
推荐答案
创建一个封装您要对每个文件执行的功能的函数.
Create a function that encapsulates what you want to do to each file.
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()
然后将此功能应用于文件名列表,如下所示:
Then apply this function to a list of filenames, like so:
for f in files:
parse_pdf(f)
这篇关于如何将我的python代码一次应用于文件夹中的所有文件,以及如何为每个后续输出文件创建新名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!