文件.写入()跳转到Python2.7的随机位置

2024-07-02 12:10:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在翻译和文件.写入()方法很奇怪,我希望有人能解释一下。在

>>> file.seek(0)
>>> file.tell()
0
>>> file.readline()
'The Project Gutenberg EBook of The Adventures of Sherlock Holmes\n'
>>> file.tell()
65
>>> file.realine()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'realine'
>>> file.readline()
'by Sir Arthur Conan Doyle\n'
>>> file.tell()
91
>>> file.write("line\n")
>>> file.tell()
4101
>>> 

为什么文件.写入(“line\n”)使其跳转到4101?在

文件是以r+模式打开的http://norvig.com/big.txt的副本


Tags: 文件ofthe方法projectreadlinelineseek
2条回答

Python的一些实现使用read-ahead buffer for ^{}.,因此在调用readline之后,filehandle的位置不一定是在刚刚读取的行的末尾。在

这里的工作不仅仅是缓冲区:如果要混合读写文件,则必须在从读到写或从写到读之间执行文件定位操作(如seek())“必须”意味着行为是未定义的-它可能在任何给定的平台上工作,也可能看起来不起作用,在一个平台上可能在某些情况下有效,但在其他情况下不起作用。这是我在2005年给出的答案的链接(哈哈!这是一个老问题),其中包含对C标准的引用(Python的大部分文件I/O行为都是从平台C库继承的):

https://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html

相关问题 更多 >