Python-For循环问题
我试图创建一个循环,遍历~3000.xml文件,搜索特定行,并打印成一个txt文件 我可以在一个xml上使用的原始代码是:Python-For循环问题,python,Python,我试图创建一个循环,遍历~3000.xml文件,搜索特定行,并打印成一个txt文件 我可以在一个xml上使用的原始代码是: my_file = open(r'C:\temp\20160309_test_xml\out.txt', 'w') with open(r'C:\temp\20160309_test_xml\test.xml', 'r') as file: for name, lines in enumerate(file, 1): if "OBJNAM" in
my_file = open(r'C:\temp\20160309_test_xml\out.txt', 'w')
with open(r'C:\temp\20160309_test_xml\test.xml', 'r') as file:
for name, lines in enumerate(file, 1):
if "OBJNAM" in lines:
my_file.write(file.next())
with open(r'C:\temp\20160309_test_xml\test.xml', 'r') as file:
for number, line in enumerate(file, 1):
if "srfres" in line:
my_file.write(file.next())
file.close()
我已尝试为此创建循环,但输出txt打印为空白:
import glob
import os
path = r'C:\temp\test_xml'
xml_directory = os.path.join(path, '*.xml')
xml_list = glob.glob(xml_directory)
my_file = open(r'C:\temp\20160309_test_xml\out.txt', 'w')
for xml in xml_list:
for name, lines in enumerate(xml, 1):
if "OBJNAM" in lines:
my_file.write(file.next())
for xml in xml_list:
for number, line in enumerate(xml, 1):
if "srfres" in line:
my_file.write(xml.next())
my_file.close()
print
或者你可以试着理解列表
[(name,lines) for name,lines in enumerate(xml_list)]
看起来您并没有在循环中打开文件,而是在路径上迭代 关于您的代码,我有一些建议: 您可以像这样迭代文件行:
with open(path, 'r') as file:
for line in file:
print line
另外,在处理xml文件时,也许可以使用
xml
lib 看起来你没有打开所有文件。什么是.next(),为什么要使用它?您是否应该使用“lines”变量?我正在使用.next()在我正在搜索的单词下方拉出一行,因为每个文本文件中都有相同的单词,但每次都不在同一行上,例如,我正在搜索OBJNAME以拉出属性名(值):
<2014 HI1447 Blakeney Overfalls 1m CUBE(单独的行)可能与此相关:
import glob
import os
xmlDir = r'C:\temp\test_xml'
xmlFiles = glob.glob(os.path.join(xmlDir, "*.xml"))
outfilepath = r'C:\temp\20160309_test_xml\out.txt'
keywords = ['OBJNAM', 'srfres']
copy = False
with open(outfilepath, 'w') as outfile:
for fpath in xmlFiles:
with open(fpath) as infile:
for line in infile:
if copy: outfile.write(line)
if any (w in line for w in keywords):
copy = True
continue
else:
copy = False
continue
import glob
import os
xmlDir = r'C:\temp\test_xml'
xmlFiles = glob.glob(os.path.join(xmlDir, "*.xml"))
outfilepath = r'C:\temp\20160309_test_xml\out.txt'
keywords = ['OBJNAM', 'srfres']
copy = False
with open(outfilepath, 'w') as outfile:
for fpath in xmlFiles:
with open(fpath) as infile:
for line in infile:
if copy: outfile.write(line)
if any (w in line for w in keywords):
copy = True
continue
else:
copy = False
continue