问题描述
我正在读取与此类似的文本文件:
...
#9 1.11 2.22
#10 3.33 4.44
#11 5.55 6.66
#12 7.77 8.88
#13 6.999 0.189
...
某些行可能存在或不存在的地方,例如从#13
行开始。
我想做的就是测试这种情况下的文本文件,如果经过验证,则取先前几行中的值(而不仅仅是前一行),说#9:
for test in open('example.txt'):
line = test.split()
if test.find("#13") != -1:
collect.append(line[1]) # <-- here should be the value from the line starting with "#9"
在python中最合适的方法是什么?
解决方法
我不知道为什么在示例中#13
将需要带有#9
的行,但是根据您的描述,您可以使用一个额外的变量来跟踪上一行:
prevline = []
for test in open('example.txt'):
line = test.split()
if test.find("#13") != -1:
collect.append(prevline[1])
prevline = line
,
collect = []
with open("example.txt") as file:
prevLine = file[0]
for line in file[1:]:
if "#13" in line:
collect.append(prevLine.split(" ")[1:])
prevLine = line
这将打开文件并读取所有行。找到包含"#13"
的行时,会将所有数字添加到列表collect
中,该列表出现在前一行的标签(#+一个数字)之后。如果"#13"
不在该行中,它将把该行存储为前一行。
鉴于文件很小(大约20行),只需使用r
读取整个文件:
readlines()
或with open(filename,'rt') as f:
lines = f.readlines() # this keeps the \n on each line
和read()
:
splitlines()
然后做测试,返回相应的行:
with open(filename,'rt') as f:
lines = f.read().splitlines() # this strips trailing whitespace on each line