Mac上的Python readline()

som*_*me1 2 python macos file-io

python的新手,并试图学习文件i/o的绳索.

使用以下格式从大型(200万行)文件中拉取行:

56fr4
4543d
4343d
hirh3
Run Code Online (Sandbox Code Playgroud)

我一直在读readline()是最好的,因为它不会将整个文件拉入内存.但是当我尝试阅读它上面的文档时,它似乎只是Unix?我在Mac上.

我可以在Mac上使用readline而无需将整个文件加载到内存中吗?简单地在文件中读取数字3的语法是什么?文档中的示例有点过头了.

编辑

这是返回代码的函数:

def getCode(i):
    with open("test.txt") as file:
        for index, line in enumerate(f):
            if index == i:
                code = # what does it equal?
                break
    return code
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 11

你不需要readline:

with open("data.txt") as file:
    for line in file:
        # do stuff with line
Run Code Online (Sandbox Code Playgroud)

这将逐行读取整个文件,但不是一次读取所有文件(因此您不需要所有内存).如果要中止读取文件,因为找到了所需的行,请使用break终止循环.如果您知道所需行的索引,请使用:

with open("data.txt") as file:
    for index, line in enumerate(file):
        if index == 2: # looking for third line (0-based indexes)
            # do stuff with this line
            break # no need to go on
Run Code Online (Sandbox Code Playgroud)