无法从python中的另一个文本文件中将打印文件打印到textfile中

时间:2018-04-02 21:05:02

标签: python python-2.7

尝试使用代码从repo中的特定目录中提取所有.xml文件名,然后筛选出包含某个关键字的所有文件。拉取文件名并将其放入第一个文本文件的代码部分可以正常工作。获取第一个文本文件并将其过滤到第二个文本文件的第二部分无法按预期工作。我没有收到错误或任何东西,但行数组是空的,这是奇怪的,因为文本文件不是。我想知道是否有人看到任何明显的我错过了我已经在这很长一段时间因此很容易错过简单的事情任何帮助将不胜感激。我已经研究了其他的例子,他们这样做的方式与我逻辑上的相似,只是不确定我哪里出错了。提前谢谢

这是代码:

#!/usr/bin/python

import glob
import re 
import os
import fnmatch
from pprint import pprint
import xml.etree.ElementTree as ET
import cPickle as pickle


#open a text output file
text_file = open("TestCases.txt", "w")
matches = []
#initialize the array called matches with all the xml files in the selected directories (bbap, bbsc, bbtest, and bbrtm

for bbdir in ['bbap/nr', 'bbsc/nr','bbtest/nr', 'bbrtm/nr']:
    for root, dirnames,filenames in os.walk('/repo/bob/ebb/'+bbdir):
        for filename in fnmatch.filter(filenames, '*.xml'):
            matches.append(os.path.join(root,filename))

#for each listing in matches test it against the desired filter to achieve the wanted tests 
for each_xml in matches:
    if each_xml.find('dlL1NrMdbfUPe') != -1:
        tree = ET.parse(each_xml)
        root = tree.getroot()
        for child in root: 
            for test_suite in child:
                for test_case in test_suite:
                    text_file.write(pickle.dumps(test_case.attrib))         

#modify the text so it is easy to read
with open("TestCases.txt") as f:
    with open("Formatted_File", "w") as f1:
        for line in f:
            if "DLL1NRMDBFUPE" in line:
                f1.write(line)

1 个答案:

答案 0 :(得分:0)

正如我所预料的那样,错误是因为查看代码的时间过长。我只是忘了在打开f之前关闭text_file。

修正:

import glob
import re 
import os
import fnmatch
from pprint import pprint
import xml.etree.ElementTree as ET
import cPickle as pickle


#open a text output file
text_file = open("TestCases.txt", "w")
matches = []
#initialize the array called matches with all the xml files in the selected directories (bbap, bbsc, bbtest, and bbrtm

for bbdir in ['bbap/nr', 'bbsc/nr','bbtest/nr', 'bbrtm/nr']:
    for root, dirnames,filenames in os.walk('/repo/bob/ebb/'+bbdir):
        for filename in fnmatch.filter(filenames, '*.xml'):
            matches.append(os.path.join(root,filename))

#for each listing in matches test it against the desired filter to achieve the wanted tests 
for each_xml in matches:
    if each_xml.find('dlL1NrMdbfUPe') != -1:
        tree = ET.parse(each_xml)
        root = tree.getroot()
        for child in root: 
            for test_suite in child:
                for test_case in test_suite:
                    text_file.write(pickle.dumps(test_case.attrib))         
**text_file.close()**

#modify the text so it is easy to read
with open("TestCases.txt") as f:
    with open("Formatted_File", "w") as f1:
        for line in f:
            if "DLL1NRMDBFUPE" in line:
                f1.write(line)
f.close()
f1.close()
相关问题