为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

烙印99 2024-01-27 16:37:26
我想逐行读取文件,但我想每两次读取时移动行指针。该文件看起来像100200300400所以,如果我写line_1 = f.readline()  # 100line_2 = f.readline()  # 200然后在第三个 readline 上,我将得到 300。我想通过 readline 得到 100,而我想通过增量语句得到 200。然后我将把它们放入一个循环中,最后我想以这种方式获取这些行:iteration #1: 100 and 200iteration #2: 200 and 300iteration #3: 300 and 400我怎样才能做到这一点?
查看完整描述

3 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

您可以创建一个生成器(它也会删除 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 200

200 and 300

300 and 400

通过这种方法,仅读取两行并将其保存在内存中。因此,它也适用于可能需要考虑内存问题的大文件。


查看完整回答
反对 回复 2024-01-27
?
守候你守候我

TA贡献1802条经验 获得超10个赞

我总是喜欢简单易读的解决方案(尽管有时不太“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  200

200 and  300

300 and  400


查看完整回答
反对 回复 2024-01-27
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

现在我建议像这样将文档分成换行符


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 语句来解决它


查看完整回答
反对 回复 2024-01-27
  • 3 回答
  • 0 关注
  • 38 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信