【问题标题】:processing multiple xml files and saving all the output inside a single .txt file处理多个 xml 文件并将所有输出保存在单个 .txt 文件中
【发布时间】:2019-05-04 13:11:26
【问题描述】:

我通过python实现,解析单个XML文件并处理它,输入和输出(多行)如下:

address = glob.glob('*.xml')
#print(address)
for single_add in address:
    xmlfile = single_add  
    items = parseXML(xmlfile)
    # species here is a list like this:
    # ['Neutrophil', 'Neutrophil', 'Microcyte', 'Giant platelet',   #'Microcyte', 'Platelet', 'Microcyte', 'Large platelet', 'Platelet', #'Platelet', 'Microcyte', 'Platelet', 'Large platelet', 'Microcyte', #'Platelet', 'Microcyte', 'Platelet', 'Microcyte', 'Platelet', #'Microcyte', 'Microcyte', 'Microcyte', 'Microcyte'] 
    print("Total no. of species provided are ")
    print(len(species))
    print(unique(species)) 
# unique just returns a list like this:
# [('Microcyte', 11), ('Large platelet', 2), ('Platelet', 7), #('Neutrophil', 2), ('Giant platelet', 1)] 

现在我有终端中所有 xml 文件的输出,如何将整个多行输出保存在单个 txt 文件中,

【问题讨论】:

  • 这 3 个打印语句是否意味着要作为目标行保存到文件中?
  • 您可以按以下方式运行脚本(如果您使用的是 Mac 或 Linux)。 python your_script.py > outputfile.txt
  • @RomanPerekhrest 是的先生,实际上这些是文件的输出,例如该 xml 文件的摘要,我想将其保存为单个目录文件中的所有其他 xml 文件

标签: python json glob os.path


【解决方案1】:

将打印语句替换为:

with open('filename.txt', 'a') as out_file:
    out_file.write("Total no. of species provided are\n{}\n{}\n".format(
        len(species),
        unique(species)))

This article 在 python 中对文件处理做了很好的描述

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多