我想在每次运行程序时读取文件的特定行。
说一个文本文件
line 1
line 2
line 3
line 4
line 5
line 6
每次运行时,我都想读取文件的每三行。
with open("test.txt", "r+") as f:
for line in f:
line = f.readline()
#do something with line
上面的代码只读取第一行,或者它只是选择要读取的行,我想要具体。每三行一次。 枚举确实允许我读取特定的行,但是逐个评估它们就是问题。 我该怎么做?
答案 0 :(得分:0)
以下是一个例子:
def _read(file, step, start=0):
with open(file, "r") as f:
for line in f.readlines()[start::step]:
print(line.strip())
_read('test.txt', 3, 2)
输出:
line 3
line 6
line 9
以下是class
:
class Reader:
def __init__(self, file_name, mode='r', start=0, step=1):
self.file = open(file_name, mode)
self.lines = self.file.readlines()[start::step]
self.file.close()
def get_line(self):
if self.lines:
return self.lines.pop(0).strip()
else:
print('No more lines')
r = Reader('test.txt', start=2, step=3)
print(r.get_line())
print(r.get_line())
print(r.get_line())
print(r.get_line())
print(r.get_line())
输出:
line 3
line 6
line 9
No more lines
None
No more lines
None