Python:file.write()未在当前file.tell()位置写入

我从文本文件中读取一行,然后在同一文件中立即写入一个字符串。但是,字符串写在文件末尾,而不是当前文件位置。 write以错误的位置书写的原因是什么?如何使write写入正确的文件位置?

代码如下:

首先,我创建一个包含两行文本的文件:

>>> file_test_01 = open('test_01.txt','w')
>>> 
>>> file_test_01.write('Firstword\n')
10
>>> file_test_01.write('Secondword\n')
11
>>> file_test_01.close()

现在,文件test_01.txt具有以下内容:

Firstword
Secondword

然后我从文件中读取一行,然后写一些东西。尽管tell在文件中的位置为10,但文本"New"被写在文件的末尾。有什么问题吗?

>>> file_test_02 = open('test_01.txt','r+')
>>> read_text = file_test_02.readline()
>>> read_text
'Firstword\n'
>>> print('Position: ',file_test_02.tell())
Position:  10
>>> file_test_02.write('New\n')
4
>>> file_test_02.close()

文本文件看起来像这样

Firstword
Secondword
New

根据我对文件操作的理解,它应该如下所示:

Firstword
New
ndword

尽管如此,如果我添加命令file_test_02.seek(file_test_02.tell()),则文件内容将如预期的那样。但这对我来说毫无意义,因为该命令说的是:“转到您实际所在的位置”,即完全多余。

有效的完整代码是

>>> file_test_02 = open('test_01.txt',file_test_02.tell())
Position:  10
>>> file_test_02.seek(file_test_02.tell())
10
>>> file_test_02.write('New\n')
4
>>> file_test_02.close()

注意:在Linux和Python 3.7.6中,Python 3.5.2(默认值,2019年10月8日,13:06:37)[GCC 5.4.0 20160609]也会发生相同的行为(默认值,2019年12月19日,23:49:42) Linux上的[GCC 5.4.0 20160609]

ainichong 回答:Python:file.write()未在当前file.tell()位置写入

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2812451.html

大家都在问