【问题标题】:How to create for-loop that does not overwrite the output xml?如何创建不覆盖输出 xml 的 for 循环?
【发布时间】:2025-12-03 21:35:01
【问题描述】:

我有一个巨大的 pdf 文件目录,我需要将其解析为 xml 文件。然后需要将这些 xml 文件转换为 xlsx(使用 pandas df)。我已经为后者编写了代码并且它正在工作,但我一直在搞清楚这个for-loop。

这是循环:

import io
from xml.etree import ElementTree
from pprint import pprint
import os
from os.path import isfile, join
import pandas as pd
from os import listdir

directory = '/jupyter/pdf_script_test/pdf_files_test'
i = 1
for filename in os.listdir(directory):
    print(filename)
    if filename.endswith('.pdf'):
        pathname = os.path.join(directory, filename)
        # attempt to assign variable name
        filename = 'new_output%s' %i
        os.system('dumppdf.py -a' + pathname + '>new_output.xml')
        i = i + 1
else:
    print('invalid pdf file')

所以我可以很快看到,每次循环迭代时,它都会用之前的 pdf 文件覆盖 "new_output.xml"。我试图找到一种方法来分配变量名或者创建一个有助于解决问题的嵌套循环。我最大的问题是如何将dumppdf.py 合并到这个循环中。

也许是一个看起来像这样的嵌套循环:

# code from above here...
data = os.system('dumppdf.py -a' + pathname) # etc..
with open('data' + str(i) + '.xml', 'w') as outfile:
    f.write()

【问题讨论】:

  • 在您的os.system 调用中使用>>new_output.xml(注意两个括号而不是一个),这样它将追加而不是覆盖该文件。尽管使用 os.system 调用另一个 python 脚本,但这是一种非常奇怪的做事方式。
  • 谢谢,这阻止了输出覆盖自身。我同意这是一个奇怪的设置,但我不确定如何在这种情况下合并 dumppdf.py。它是唯一可以将 pdf 文件成功转换为 xml 格式的方法。 PyPDF2 和其他人无法工作,因为他们将所有填写的表单区域留空..

标签: python python-3.x for-loop pdf xml-parsing


【解决方案1】:

这是我最终解决问题的方法:

import io
from xml.etree import ElementTree
from pprint import pprint
import os
from os.path import isfile, join
import pandas as pd
from os import listdir

directory = '/jupyter/pdf_script_test/pdf_files_test/'
patient_number = 1 #variable name 

#loop over pdf files and write a new .xml for each pdf file. 
for filename in os.listdir(directory):
    print(filename)
    if filename.endswith(".pdf"):
        pathname = os.path.join(directory, filename)
#Run dumppdf.py on the pdf file and write the .xml using the assigned variable
        data = os.system('dumppdf.py -a ' + pathname + ' > ' + str(patient_number) + '.xml') 
        patient_number = patient_number + 1
 
    else:
        print("invaild pdf file")  
    

【讨论】: