我正在尝试使用 python 读取文本文件。代码如下:
with open('data.txt') as f:
for line in f:
val=line.split()
它只是从文本文件中读取并确保一次读取所有行。我想改变它的实现。假设它在一个函数中,并且我有一个已经打开的文件,如何确保我每次调用该函数时都读取一个新行?
我已经了解了 seek
函数,我可以在每次调用该函数时使用它来寻找新行吗?
最佳答案
您可以使用生成器,如下所示
def get_next_line(file_name):
with open(file_name) as f:
for line in f:
yield line.strip()
你可以得到下一行,就像这样
for line in get_next_line("Input.txt"):
print line
但是您想要获取下一行,而不是在循环中,那么您可以显式使用 next
函数,如下所示
my_file = get_next_line("Input.txt")
print next(my_file)
print next(my_file)
关于python - 从文件读取: find the new line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801514/