处理多个xml文件并将所有输出保存在单个.txt文件中

时间:2019-05-04 13:11:26

标签: python json glob os.path

我通过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文件中,

1 个答案:

答案 0 :(得分: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中的文件处理方式