簡體   English   中英

Python的'a +'文件打開模式中的錯誤?

[英]Bug in Python's 'a+' file open mode?

我目前正在使用python-fuse創建一個文件系統,並且查找文件指針在每個不同模式('r','r +'等)的起始位置,並在多個站點上找到文件指針從零開始,除非當它從文件末尾開始時,它在'a'或'a +'中打開。

我在Python中測試了這個以確保(在每個模式中打開一個文本文件並立即調用tell())但發現當它在'a +'中打開時,文件指針為零而不是文件的末尾。

這是python中的錯誤,還是網站錯了?

以供參考:

不,這不是一個錯誤。

寫完一些數據調用tell()會發生什么?

它是按照您的預期寫在位置0還是文件末尾? 我幾乎打賭我的生活是后者。

>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
15
>>> f.close()
>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
30

因此,它會寫入數據之前尋找文件的末尾。

這應該是這樣的。 fopen()手冊頁:

  a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file. 

Phew,幸運的是我是對的。

我不認為這是一個錯誤(雖然我不完全明白這是什么)。 文檔說:

...'a'用於追加(在某些Unix系統上意味着所有寫入都附加到文件的末尾而不管當前的搜索位置)

這確實發生了什么:

In [3]: hello = open('/tmp/hello', 'w')

In [4]: hello.write('Hello ')

In [5]: hello.close()

In [6]: world = open('/tmp/hello', 'a+')

In [7]: world.write('world!')

In [8]: world.close()

In [9]: open('/tmp/hello').read()
Out[9]: 'Hello world!'

我在Ubuntu上,而tell()也在a+模式下返回0

傳遞給open()的模式只是傳遞給C fopen()函數。 a+應該將流的位置設置為0,因為文件被打開以進行讀取和追加。 在大多數unix系統(可能還有其他地方)上,所有寫操作都將在文件末尾完成,無論你在哪里seek()編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM