在追加模式下写入指定位置

人气:317 发布:2022-10-16 标签: file python append

问题描述

在PYTHON中我发现:

a=open('x', 'a+')
a.write('3333')
a.seek(2)       # move there pointer
assert a.tell() == 2  # and it works
a.write('11')   # and doesnt work
a.close()
给出了x文件中的333311,但我们使用2字节偏移量进行了第二次写入,而不是4字节, 因此,即使更改了文件流指针,Seek也无法在那里执行写入操作。

=>我的问题是:它是更流行语言的编程标准吗?

推荐答案

来自http://docs.python.org/2.4/lib/bltin-file-objects.html的文档:

请注意,如果打开文件以进行追加(模式为‘a’或‘a+’),则在下一次写入时将撤消所有Seek()操作。

'r+'模式打开文件,即"读写"模式。

849