How to Open a File for Both Reading and Writing

How to open a file in both read and append mode at the same time in one variable in python?

You're looking for the r+/a+/w+ mode, which allows both read and write operations to files.

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

with open("filename", "r+") as f:
# here, position is initially at the beginning
text = f.read()
# after reading, the position is pushed toward the end

f.write("stuff to append")
with open("filename", "a+") as f:
# here, position is already at the end
f.write("stuff to append")

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

with open("filename", "r+") as f:
text = f.read()
f.write("stuff to append")

f.seek(0) # return to the top of the file
text = f.read()

assert text.endswith("stuff to append")

(Further Reading: What's the difference between 'r+' and 'a+' when open file in python?)

You can also use w+, but this will truncate (delete) all the existing content.

Here's a nice little diagram from another SO post:

Decision Tree: What mode should I use?

(source)

Reading and writing a file using two file objects in Python 3.x

The file data can be flushed without ever closing by using f.flush()

now the pipe like behavior I wanted can be implemented as follow

>>> f1 = open('filename','w')
>>> f2 = open('filename', 'r')
>>> f1.write('test string')
11
>>> f1.flush()
>>> f2.read()
'test string'

still my other two questions are unanswered..

does f2.read() function tries to read directly from the disk or from the already available buffer cache of the file?

when will the updated file written back to the disk?

I will find it soon...

Beginner Python: Reading and writing to the same file

Updated Response:

This seems like a bug specific to Windows - http://bugs.python.org/issue1521491.

Quoting from the workaround explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html

the effect of mixing reads with writes on a file open for update is
entirely undefined unless a file-positioning operation occurs between
them (for example, a seek()). I can't guess what
you expect to happen, but seems most likely that what you
intend could be obtained reliably by inserting

fp.seek(fp.tell())

between read() and your write().

My original response demonstrates how reading/writing on the same file opened for appending works. It is apparently not true if you are using Windows.

Original Response:

In 'r+' mode, using write method will write the string object to the file based on where the pointer is. In your case, it will append the string "Test abc" to the start of the file. See an example below:

>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\n'
>>> f.write("foooooooooooooo")
>>> f.close()
>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\nfoooooooooooooo'

The string "foooooooooooooo" got appended at the end of the file since the pointer was already at the end of the file.

Are you on a system that differentiates between binary and text files? You might want to use 'rb+' as a mode in that case.

Append 'b' to the mode to open the file in binary mode, on systems
that differentiate between binary and text files; on systems that
don’t have this distinction, adding the 'b' has no effect.
http://docs.python.org/2/library/functions.html#open

how to open fstream for both reading and writing operation in Visual Studio

Simple code.

stream file;
file.open(fileName,ios::in | ios::out);

The symbol to be used between flags is the piping symbol.



Related Topics



Leave a reply



Submit