简体   繁体   English

追加并读取文件的最后一行

[英]Append and read last line of file

Is there a way to append to a file and read it with the same "open" file command in Python3.7? 有没有一种方法可以附加到文件并在Python3.7中使用相同的“打开”文件命令读取文件? I mean I do not want to have two open statements, one for open("//", "a") and one for open("//", "r"). 我的意思是我不想有两个open语句,一个用于open(“ //”,“ a”),另一个用于open(“ //”,“ r”)。 What I am trying to achieve is run a script which appends the output to the file, and then read the last line of the file. 我要实现的目标是运行一个脚本,该脚本将输出追加到文件中,然后读取文件的最后一行。 "a+" does not help; “ a +”无济于事; it gives a index of out range for readlines()[-1]. 它为readlines()[-1]提供了超出范围的索引。

Thanks in advance. 提前致谢。

Opening the file in a+ makes the file pointer point to the end of the file, which makes it hard to read the last line. a+打开文件会使文件指针指向文件的末尾,这使得很难读取最后一行。 You can instead open the file in r+ mode, iterate over the file object until you obtain the last line, and then append the additional output to the file: 您可以改为在r+模式下打开文件,遍历文件对象,直到获得最后一行,然后将其他输出附加到文件:

with open('file', 'r+') as file:
    for line in file:
        pass
    file.write(output)

# variable line now holds the last line
# and the file now has the content of output at the end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM