您可以从带有open(fname,'a +')的文件中读取第一行吗?

use*_*153 4 python file python-3.x

我希望能够打开一个文件,在末尾附加一些文本,然后仅读取第一行。我确切知道文件的第一行有多长时间,并且文件足够大,我不想一次将其全部读入内存。我试过使用:

with open('./output files/log.txt', 'a+') as f:

    f.write('This is example text')

    content = f.readline()
    print(content)
Run Code Online (Sandbox Code Playgroud)

但是打印语句为空。当我尝试使用open('./output files/log.txt')或open('./output files/log.txt', 'r+')代替open('./output files/log.txt', 'a+')它工作时,所以我知道它与'a+参数有关。我的问题是我必须附加到文件。我如何追加到文件并仍然获得第一行而不使用类似的东西

with open('./output files/log.txt', 'a+') as f_1:

    f.write('This is example text')

    with open('./output files/log.txt') as f_2:
        content = f_2.readline()
        print(content)
Run Code Online (Sandbox Code Playgroud)

xgo*_*ord 5

当使用append标志打开文件时a,它将文件描述符的指针移到文件末尾,这样write调用将添加到文件末尾。

该readline()函数从文件的当前指针读取,直到'\n'读取下一个字符为止。因此,当您使用append打开文件,然后调用时readline,它将尝试读取从文件末尾开始的一行。这就是为什么您的print通话空白的原因。

您可以file使用tell()函数查看对象当前指向的位置,从而实际地看到这一点。

要读取第一行,必须确保文件的指针位于文件的开头,可以使用seek函数来完成。seek 有两个参数:offset和from_what。如果省略第二个参数,offset则从文件开头开始。因此,要跳至文件的开头,请执行:seek(0)。

如果要跳回到文件末尾,可以包括该from_what选项。from_what=2表示从文件末尾开始的偏移量。因此,请跳到最后:seek(0, 2)。


在追加模式下打开文件时,将演示文件指针:

使用文本文件的示例如下所示:

the first line of the file
and the last line
Run Code Online (Sandbox Code Playgroud)

码:

with open('example.txt', 'a+') as fd:
    print fd.tell() # at end of file
    fd.write('example line\n')
    print fd.tell() # at new end of the file after writing

    # jump to the beginning of the file:
    fd.seek(0)
    print fd.readline()

    # jump back to the end of the file
    fd.seek(0, 2)
    fd.write('went back to the end')
Run Code Online (Sandbox Code Playgroud)

控制台输出:

45
57
the first line of the file
Run Code Online (Sandbox Code Playgroud)

的新内容example.txt:

the first line of the file
and the last line
example line
went back to the end
Run Code Online (Sandbox Code Playgroud)


编辑:添加了跳回到文件末尾