我希望能够打开一个文件,将一些文本附加到末尾,然后仅读取第一行。我确切地知道文件的第一行有多长时间,并且文件足够大,我不想一次将其全部读入内存。我试过使用:
with open('./output files/log.txt', 'a+') as f:
f.write('This is example text')
content = f.readline()
print(content)
但是打印语句为空。当我尝试使用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)
当使用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
代码:
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
编辑:添加了跳回到文件末尾
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句