In python, there are a few flags you can supply when opening a file for operation. I am a bit baffled at finding a combination that allow me to do random write without truncating. The behavior I am looking for is equivalent to C: create it if it doesn't exist, otherwise, open for write (not truncating)
open(filename, O_WRONLY|O_CREAT)
Python's document is confusing (to me): "w"
will truncate the file first, "+"
is supposed to mean updating, but "w+"
will truncate it anyway. Is there anyway to achieve this without resorting to the low-level os.open()
interface?
Note: the "a"
or "a+"
doesn't work either (please correct if I am doing something wrong here)
cat test.txt
eee
with open("test.txt", "a+") as f:
f.seek(0)
f.write("a")
cat test.txt
eeea
Is that so the append mode insist on writing to the end?
What is the use of ios::trunc mode? Explanation: In C++ file handling, ios::trunc mode is used to truncate an existing file to zero length. 8.
Without parameters, truncate() acts like w, whereas w always just wipes the whole file clean. So, these two methods can act identically, but they don't necessarily.
In databases and computer networking data truncation occurs when data or a data stream (such as a file) is stored in a location too short to hold its entire length.
In some situations, you might want to truncate (empty) an existing file to a zero-length. In simple words, truncating a file means removing the file contents without deleting the file. Truncating a file is much faster and easier than deleting the file , recreating it, and setting the correct permissions and ownership .
You can do it with os.open:
import os
f = os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT), 'rb+')
Now you can read, write in the middle of the file, seek, and so on. And it creates the file. Tested on Python 2 and 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With