我希望能够打开一个文件,在末尾添加一些文本,然后只读取第一行。我确切地知道文件的第一行有多长,文件足够大,我不想一次将它读入内存。我尝试过使用:
with open('./output files/log.txt', 'a+') as f:
f.write('This is example text')
content = f.readline()
print(content)
但是print语句是空白的。当我尝试使用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)
答案 0 :(得分:4)
当您使用追加标志write
打开文件时,它会将文件描述符的指针移动到文件的末尾,以便readline()
调用将添加到文件的末尾。
'\n'
函数从文件的当前指针读取,直到它读取的下一个readline
字符。因此,当您打开带有追加的文件,然后调用print
时,它将尝试从文件末尾开始读取一行。这就是您的file
来电空白的原因。
通过使用tell()
函数查看seek
对象当前指向的位置,您可以看到这一点。
要读取第一行,您必须确保文件的指针返回到文件的开头,您可以使用seek
功能执行此操作。 offset
takes two arguments:from_what
和offset
。如果省略第二个参数,则从文件的开头取seek(0)
。因此,要跳转到文件的开头,请执行:from_what
。
如果要跳回文件末尾,可以包含from_what=2
选项。 seek(0, 2)
表示从文件末尾获取偏移量。所以跳到最后:the first line of the file
and the last line
。
在附加模式下打开时演示文件指针:
使用如下文本文件的示例:
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')
代码:
45
57
the first line of the file
控制台输出:
example.txt
the first line of the file
and the last line
example line
went back to the end
的新内容:
web: vendor/bin/heroku-php-apache2 web/
编辑:添加跳回文件末尾
答案 1 :(得分:1)
您需要使用seek(0)
返回文件的开头,如下所示:
with open('./output files/log.txt', 'a+') as f_1:
f_1.write('This is example text')
f_1.seek(0)
print(f_1.readline())