【问题标题】:Python parser - defining output filenamesPython 解析器 - 定义输出文件名
【发布时间】:2019-04-05 10:33:20
【问题描述】:

一个初学者的问题 - 我有一个 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文件的名字,把“输出”放在前面。

【问题讨论】:

  • 你是在递归解析目录中的所有文件吗?
  • 是的,或者我至少想要。

标签: python python-3.x parsing saxparser


【解决方案1】:

您可以取输入文件名,将其拆分以获取句点之前的部分,然后添加/附加“输出”和“.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")

【讨论】:

  • 谢谢。使用这种方法,我应该在哪里指定输入目录?我收到如下错误: Traceback (最近一次调用最后一次): File "C:/Users/mypath/parser.py", line 5, in for xmlfile in listofffiles: NameError: name 'listoffiles' is未定义
  • listoffiles 应该在 for 循环之前定义。编辑我的答案。
  • 好东西 - 谢谢!我不得不将一行改写为txtfile = xmlfile.split(".")[0] + "output.txt" 以阻止它将“输出”放在文件路径的开头,并且通过该更改,它完全符合我的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 2020-07-30
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多