我有python的读入问题。我是那个公司的新手......
该计划的部分内容如下:
for line in f.readlines():
if ... :
print(line)
是否有可能,不仅打印该行,还有下一行? (即使它不符合if ...)
我尝试过:
for k,line in enumerate(f.readlines())
但我不知道如何用数字(k)打印一行
这个问题有没有简单的解决方案?
答案 0 :(得分:2)
将行列表存储在变量中:
lines = f.readlines()
for k, line in enumerate(lines):
# line - current line
# lines[k + 1] - next line
请注意,在访问k < len(lines) - 1
之前,您应该先检查lines[k + 1]
。
上述方法以及您的原始方法需要将整个文件预先加载到内存中。如果要保存一些内存,可以逐步从文件中读取循环读取行:
def iter_lines(f):
"""Iterate over lines in f, providing the current and next line."""
it = iter(f)
this_line = None
for this_line in it:
break # only get first line
else:
return # no lines in the file
for next_line in it:
yield this_line, next_line
this_line = next_line
yield this_line, None
for line, next_line in iter_lines(f):
# line: current line
# next_line: next line, or None if at the last line
答案 1 :(得分:0)
您无需将整个文件读入内存即可:
prev = None
for line in f:
if prev is None:
prev = line
else:
print prev + line
prev = line