用于将 txt 文件转换为 pdf 的循环 - 仅适用于第一个文件

For loop to convert txt files to pdf - only working on first file

我有一个包含 .txt 文件的文件夹,我需要将其转换为 pdf。我已经成功地为 1 个 .txt 文件完成了此操作,但我想完成所有 126 个(最好不是手动,一次一个)。我将工作代码放入 for 循环中以遍历文件夹中的每个文件。代码运行,没有错误。然而,这是它的行为方式:

第一个文件:转换完美,没有问题。 第二个文件:再次转换第一个文件,然后在一个文档中转换第二个文件。 第三个文件,将第一个、第二个和第三个文件转换为一个文档。 等等

我尝试过的事情:

这是我的代码:

pdf = FPDF()

pdf.add_page()
pdf.set_font("Arial", size = 8)

files = os.listdir('Convert') #this is the folder where all the .txt files are

for file in tqdm(files):
    dir_full_path = os.path.abspath('Convert')
    file_full_path = os.path.join(dir_full_path, file)
    output_filename = os.path.basename(file)+'.pdf'
    
    f = open(file_full_path, 'r+')
    
    for x in f: 
        pdf.cell(200,10, txt = x, ln = 1, align = 'L')
    
    pdf.output(output_filename)

关于如何解决的任何想法? TIA

当您说“我将我的工作代码放入 for 循环中以遍历文件夹中的每个文件”时,您实际上错过了一个地方。

您需要在循环的每次迭代中创建一个新的 FPDF 对象,否则,您只是将行附加到同一行。当您调用 pdf.output(output_filename) 时,结果确实应该包含您目前已处理的所有文件的所有行。

这里有一个解决问题的例子,也展示了如何正确关闭输入文件:

files = os.listdir('Convert')
dir_full_path = os.path.abspath('Convert')

for file in tqdm(files):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size = 8)

    file_full_path = os.path.join(dir_full_path, file)
    with open(file_full_path, 'r+') as f:
        for line in f: 
            pdf.cell(200, 10, txt=line, l =1, align='L').

    output_filename = os.path.basename(file) + '.pdf'
    pdf.output(output_filename)