Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File mode for creating+reading+appending+binary

Tags:

python

file-io

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

like image 463
Mihai Damian Avatar asked May 03 '10 12:05

Mihai Damian


People also ask

Which mode is used for appending in binary file?

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like GIFs, audio files like MP3s or binary document formats like Word or PDF. To open files in binary append mode, when specifying a mode, add 'ab' to it.

What is append file mode?

It refers to how the file will be used once its opened. In order to append a new line your existing file, you need to open the file in append mode , by setting "a" or "ab" as the mode. When you open with "a" mode , the write position will always be at the end of the file (an append).


1 Answers

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\n') >>> f.seek(0, os.SEEK_SET) >>> f.readline() 'hello\n' >>> f.write('there\n') >>> f.seek(0, os.SEEK_SET) >>> f.readline() 'hello\n' >>> f.readline() 'there\n' 
like image 152
msw Avatar answered Sep 25 '22 03:09

msw