从带有 readline 偏移量的文件中读取行

我想逐行读取文件,但我想每两次读取时移动行指针。该文件看起来像


100

200

300

400

所以,如果我写


line_1 = f.readline()  # 100

line_2 = f.readline()  # 200

然后在第三个 readline 上,我将得到 300。我想通过 readline 得到 100,而我想通过增量语句得到 200。然后我将把它们放入一个循环中,最后我想以这种方式获取这些行:


iteration #1: 100 and 200

iteration #2: 200 and 300

iteration #3: 300 and 400

我怎样才能做到这一点?


烙印99
浏览 44回答 3
3回答

米琪卡哇伊

您可以创建一个生成器(它也会删除 EOL 字符,如果您想要不同的东西,您可以删除rstrip):def readpairsoflines(f):    l1 = f.readline().rstrip('\n')    for l2 in f:        l2 = l2.rstrip('\n')        yield l1, l2        l1 = l2并像这样使用它:with open(filename) as f:    for l1, l2 in readpairsoflines(f):        # Do something with your pair of lines, for example print them        print(f'{l1} and {l2}')结果:100 and 200200 and 300300 and 400通过这种方法,仅读取两行并将其保存在内存中。因此,它也适用于可能需要考虑内存问题的大文件。

守候你守候我

我总是喜欢简单易读的解决方案(尽管有时不太“Pythonic”)。with open("example.txt") as f:    old = f.readline().rstrip()        for line in f:        line = line.rstrip()        print("{} and  {}".format(old, line))        old = line在循环其余行之前执行第一次读取然后,打印所需的输出,并old更新字符串需要调用 ion命令rstrip()来删除不需要的尾随'\n'我认为如果文件少于两行,则无需打印任何内容;可以轻松修改代码以管理特殊情况下的任何需求输出:100 and  200200 and  300300 and  400

蝴蝶刀刀

现在我建议像这样将文档分成换行符with open('params.txt') as file:    data = file.read()data = data.split('\n')for index, item in enumerate(data):    try:        print(str(item) + ' ' + str(data[index + 1]))    except IndexError:        print(str(item))并使用一些列表逻辑打印您需要的内容,因此此代码的作用是创建所需值的列表(对于非常大的文件效率不高)并获取它们的索引,因此当它打印该项目时,它还会打印列表中的下一个项目,并且它对每个项目索引错误执行此操作是因为最后一项不会有下一项,但您也可以通过使用 if else 语句来解决它
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python