I want to:
- open a file in read-write mode if it exists;
- create it if it doesn't exist;
- be able to truncate it anytime-anywhere.
EDIT: with truncate I mean write until a position and discard the remaining part of the file, if present
All this atomically (with a single open()
call or simulating a single open()
call)
No single open modality seems to apply:
- r : obviously doesn't work;
- r+ : fails if the file doesn't exist;
- w: recreate the file if it exists;
- w+: recreate the file if it exists;
- a: can't read;
- a+: can't truncate.
Some combinations I tried (rw, rw+, r+w, etc.) seems to not work either. Is it possible?
Some doc from Ruby (applies to python too):
r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.
r+
Read-write mode. The file pointer will be at the beginning of the file.
w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
w+
Read-write mode. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
a
Write-only mode. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.
a+
Read and write mode. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…