2013-10-30 24 views
0

我發現:寫入到指定位置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, 所以尋找不存在的工作用於寫入,儘管文件流指針已更改。

===>我的問題:它是更流行語言的編程標準嗎?

回答

1

以追加方式的文件始終追加write() S到文件的末尾,你可以看到here

O_APPEND

如果設置,文件偏移將被設置爲結束在每次寫入之前的文件。

0

嘗試mmap。它基本上可以讓你編輯一個文件。 來自文檔:

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()