首页 > 解决方案 > Python 解析器 - 定义输出文件名

问题描述

一个初学者的问题 - 我有一个 Python SAX 解析器,它从 .xml 文件中提取文本行并将它们写入 .txt 文件。现在我希望它针对目录中的所有文件运行并从输入文件名派生输出文件名,但我无法让它工作。

解析器本身工作正常,所以在下面的代码中,我只显示了指定输入和输出文件的块。对于这样做的简单方法有什么建议吗?

# Code begins

import sys
import re
from enum import Enum

sys.stdout = open("outputab123.txt", "w", encoding="UTF-8")

import xml.sax

# ~ 50 lines of SAX parser code

# Final block of code
   parser.parse("ab123.xml")
   sys.stdout.close()

对于每个输出 .txt 文件,我只想取输入 .xml 文件的名称并将“输出”放在前面。

标签: pythonpython-3.xparsingsaxparser

解决方案


您可以获取输入文件名,将其拆分以获取句点之前的部分,然后添加/附加“输出”和“.txt”:

xmlfile = "ab123.xml"
txtfile = "output" + xmlfile.split(".")[0] + ".txt"
print(txtfile)

输出:

outputab123.txt

所以总的来说,你的代码可能看起来像:

listofiles = # define list of files here (eg. using glob)

for xmlfile in listoffiles:
    # parsing here
    parser.parse(xmlfile)
    sys.stdout.close()

    txtfile = "output" + xmlfile.split(".")[0] + ".txt"
    sys.stdout = open(txtfile, encoding="UTF-8")
    # write to text file here

要获取目录中的.xml文件列表,可以使用glob

listoffiles = glob.glob("/path/to/directory/*.xml")

推荐阅读