Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

python - File mode for creating+reading+appending+binary

I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?

I tried 'r+ab' but that doesn't create the files if they are not found.

Thanks

question from:https://stackoverflow.com/questions/2757887/file-mode-for-creatingreadingappendingbinary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page:

  • w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

  • 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.

With the "b" tacked on to make DOS happy. Presumably you want to do something like this:

>>> f = open('junk', 'ab+')
>>> f
<open file 'junk', mode 'ab+' at 0xb77e6288>
>>> f.write('hello
')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello
'
>>> f.write('there
')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello
'
>>> f.readline()
'there
'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...