python - 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 文件的名称并将“输出”放在前面。
解决方案
您可以获取输入文件名,将其拆分以获取句点之前的部分,然后添加/附加“输出”和“.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")
推荐阅读
- web-scraping - YouTube 评论刮板不工作/错误?
- javascript - 没有花括号的Javascript函数
- c++ - 命名空间内的类和 C++ 外的设置函数
- sql - 如果存在则从表 A 中获取值,否则从表 B 中获取值。如果找到多个值,则返回 MT 以指示多种类型
- git - 与私有 Git 存储库的 ssh 连接问题
- python-3.x - Selenium xpath Webelement问题
- json - JSON 对象属性名称的第一个字母正在更改为非大写字符
- html - style a parameter from server side and append it to innerHTML
- javascript - 为什么 !{}.length 在 JavaScript 中评估为 true?
- spring-boot - 如何使 Spring Boot REST 控制器异步?