Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open file for random write without truncating?

Tags:

python

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?

like image 914
Oliver Avatar asked Mar 07 '15 18:03

Oliver


People also ask

Which mode opens an existing file and truncates its content?

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.

Is The truncate () necessary with the W parameter?

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.

What is file truncation?

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.

Why do we truncate file?

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 .


1 Answers

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.

like image 122
RemcoGerlich Avatar answered Nov 06 '22 20:11

RemcoGerlich