Python 以追加模式写入指定位置
在python中,我发现:Python 以追加模式写入指定位置,python,file,append,Python,File,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在那个里还是不工作 =>我的问题:它是更
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在那个里还是不工作
=>我的问题:它是更流行语言的编程标准吗?处于附加模式的文件总是在文件末尾附加
write()
s,如您所见:
O_追加
如果已设置,则文件偏移量将设置为每次写入之前的文件末尾
从以下地址的文档:
请注意,如果打开文件进行追加(模式“a”或“a+”),则任何seek()操作都将在下一次写入时撤消
在'r+'
模式下打开文件,意思是“读写”。试试看。它基本上允许您就地编辑文件。
从文档中:
import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print mm.readline() # prints "Hello Python!"
# read content via slice notation
print mm[:5] # prints "Hello"
# update content using slice notation;
# note that new content must have same size
mm[6:] = " world!\n"
# ... and read again using standard file methods
mm.seek(0)
print mm.readline() # prints "Hello world!"
# close the map
mm.close()