我需要分别读取连续的200个文件,其名称如nwirp1.rec ........ nwirp200.rec,然后将所有单独文件中的数据提取到不同的连续文件中。我写了这样的代码。但它没有用。我的数据就像这样
参数----->
参数估计值
hklay1 3.278692E-06
kppt1 4.249307E-07
kppt2 2.849132E-06
请参阅文件nwirp_nsmc.sen了解参数敏感度。
我需要从每个文件中提取这部分
hklay1 3.278692E-06
kppt1 4.249307E-07
kppt2 2.849132E-06
并将它们写入不同的输出文件,如data1.txt ........... data200.txt
我尝试过这种方式,但它不起作用:
for i in range(1, 200):
with open('nwirp%s.upw' % i, 'r') as f:
for line in f:
if line.strip().startswith("Parameter Estimated value"):
new_file = []
line = next(f)
while not line.strip().startswith("See file"):
new_file.append(line)
line = next(f)
with open('nwirp%s.upw' % i, 'w') as outfile:
print >>outfile, "".join(new_file)
显示NameError:未定义名称'new_file'。
答案 0 :(得分:2)
您的第一行匹配(f line.strip().startswith("Parameter...
)可能无法正常运行,因此new_file
无法定义,这可能会在您尝试附加或写入时导致指定的错误下。
如果文件不是太大,而不是逐行搜索数据,我建议只使用正则表达式捕获字符串之间的线条然后用匹配的行覆盖内容来简化它: / p>
import re
matcher = re.compile(r"Estimated value\s+(.*?)\s+See file", re.DOTALL)
for i in xrange(1, 201): # replace xrange with range when using Python 3.x
with open("nwirp{}.upw".format(i), "r+") as f: # open in read-write
content = matcher.findall(f.read()) # read whole file and grab the match(es?)
f.seek(0) # go back to the beginning
f.write("".join(content)) # concatenate just in case of more matches
f.truncate() # remove the extra content
如果你想写一个不同的文件(data1 ... data200.txt),假设你想要覆盖到你正在阅读的文件,如你的代码中所表达的那样,而不是f.seek()...f.truncate()
行使用:
with open("data{}.txt".format(i), "w") as out:
out.write("".join(content)) # concatenate just in case of more matches
如果您不想使用正则表达式,只要您的匹配结构简单,就可以通过string.find()
获得类似的效果来查找第一行和最后一行'索引,然后得到这两者之间的所有内容的子字符串。