276

From the doc,

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). 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.

and here

w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

But, how to read a file open with w+?

holys
  • 13,869
  • 15
  • 45
  • 50

11 Answers11

554

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. 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.

  • ab

    Opens a file for appending in binary format. 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+

    Opens a file for both appending and reading. 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.

  • ab+

    Opens a file for both appending and reading in binary format. 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.

Kousik
  • 21,485
  • 7
  • 36
  • 59
  • so for all intensive purposes, r+ and w+ are the same? – Nick Humrich Jul 17 '14 at 22:59
  • 30
    @Humdinger: No, `w+` creates a new file or truncates an existing file, then opens it for reading and writing; `r+` opens an existing file without truncating it for reading and writing. Very different. – abarnert Aug 04 '14 at 09:31
  • 1
    Also, as with @AlokAgarwal's answer, this claims to be an exhaustive list of modes, but isn't. – abarnert Aug 04 '14 at 09:32
  • 1
    It would be rather silly to give an exhaustive list of modes, as they function more like a function with multiple parameters. `r`, `w`, or `a` are exclusive, but `b` can be added to any of those, as can `+`, or `U`... It's a combinatorial explosion. – rmunn Oct 03 '14 at 06:41
  • This answer is inconstant with the one given by @Alok Agarwal – Celeritas Jul 17 '15 at 19:52
  • 4
    `rb` is not the default mode, quote : `The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'` https://docs.python.org/2/library/functions.html#open – iggy Jul 27 '15 at 11:33
  • 2
    Maybe we can add the "x" mode, aka "exclusive creation": this creates the file (for writing) if it does not exist, and raises FileExistsError if it does not. – András Aszódi Sep 01 '15 at 14:20
  • Saying that mode "a+" places the file pointer "at the end of the file" is not exactly correct. All writes will happen at the end of the file, but reads may not. From the 2.6 docs: "Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write." In my quick experimentation on Ubuntu, "the next write" means a call to flush(), whereas write() does not change the value returned by tell(). https://docs.python.org/2/library/stdtypes.html#file.seek – Channing Moore Oct 12 '17 at 16:35
172

All file modes in Python

  • r for reading
  • r+ opens for reading and writing (cannot truncate a file)
  • w for writing
  • w+ for writing and reading (can truncate a file)
  • rb for reading a binary file. The file pointer is placed at the beginning of the file.
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • a+ opens for appending
  • ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
  • x open for exclusive creation, failing if the file already exists (Python 3)
Alok Agarwal
  • 3,071
  • 3
  • 23
  • 33
  • 5
    This isn't all the modes. It neglects, e.g., `rb` and `wb`, not to mention the `U` modes in 2.x and the `t` mode in 3.x (which can both be combined with everything except `b`). – abarnert Aug 04 '14 at 09:30
  • 1
    The difference between r+ and w+ is that w+ truncates a file when it's opened. But you can truncate it manually in both modes. – Martin Oct 07 '14 at 08:14
  • 2
    This answer is inconstant with the one given by @200 OK, for example does `wb+` also read from the file? – Celeritas Jul 17 '15 at 19:53
  • @Celeritas The wb indicates that the file is opened for writing in binary mode. On Unix systems (Linux, Mac OS X, etc.), binary mode does nothing - they treat text files the same way that any other files are treated. On Windows, however, text files are written with slightly modified line endings. This causes a serious problem when dealing with actual binary files, like exe or jpg files. Therefore, when opening files which are not supposed to be text, even in Unix, you should use wb or rb. Use plain w or r only for text files. – Alok Agarwal Aug 12 '15 at 09:06
  • In Python 3, there is also the 'x' open mode: open for exclusive creation, failing if the file already exists. See [open](https://docs.python.org/3.6/library/functions.html#open) function in the doc. – Laurent LAPORTE Oct 20 '16 at 11:49
  • What does "truncate" mean? – Eduard Mar 11 '18 at 15:34
  • @Eduard in this context, it means removing content after the pointer – Arn Feb 18 '20 at 11:24
167

Let's say you're opening the file with a with statement like you should be. Then you'd do something like this to read from your file:

with open('somefile.txt', 'w+') as f:
    # Note that f has now been truncated to 0 bytes, so you'll only
    # be able to read data that you write after this point
    f.write('somedata\n')
    f.seek(0)  # Important: return to the top of the file before reading, otherwise you'll just read an empty string
    data = f.read() # Returns 'somedata\n'

Note the f.seek(0) -- if you forget this, the f.read() call will try to read from the end of the file, and will return an empty string.

rmunn
  • 34,942
  • 10
  • 74
  • 105
  • 3
    what does "truncating to 0 bytes" mean? – Nasif Imtiaz Ohi Jan 05 '18 at 23:49
  • 31
    @NasifImtiazOhi - The Python docs say that `w+` will "overwrite the existing file if the file exists". So as soon as you open a file with `w+`, it is now an empty file: it contains 0 bytes. If it used to contain data, that data has been truncated — cut off and thrown away — and now the file size is 0 bytes, so you can't read any of the data that existed *before* you opened the file with `w+`. If you actually wanted to read the previous data and add to it, you should use `r+` instead of `w+`. – rmunn Jan 06 '18 at 08:33
  • how to add new data on top ? – Beqa Bukhradze Jul 01 '18 at 17:34
  • 3
    @BeqaBukhradze - If you have a question, click the "Ask a question" button, where it will be seen by hundreds of people. Don't just click the "Add Comment" button where only one or two people will see it. – rmunn Jul 02 '18 at 01:05
  • @BeqaBukhadraze use "a" mode – Psychzander Aug 04 '20 at 13:11
  • @rmunn what do you think about my answer? It prevents inadvertent loosing data. – Andrew Anderson Jul 13 '21 at 20:01
16

r for read

w for write

r+ for read/write without deleting the original content if file exists, otherwise raise exception

w+ for delete the original content then read/write if file exists, otherwise create the file

For example,

>>> with open("file1.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file1.txt", "w+") as f:
...   f.write("c")
... 

$ cat file1.txt 
c$
>>> with open("file2.txt", "r+") as f:
...   f.write("ab\n")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file2.txt'

>>> with open("file2.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file2.txt", "r+") as f:
...   f.write("c")
... 

$ cat file2.txt 
cb
$
GraceMeng
  • 949
  • 8
  • 6
8

Both seems to be working same but there is a catch.

r+ :-

  • Open the file for Reading and Writing
  • Once Opened in the beginning file pointer will point to 0
  • Now if you will want to Read then it will start reading from beginning
  • if you want to Write then start writing, But the write process will begin from pointer 0. So there would be overwrite of characters, if there is any
  • In this case File should be present, either will FileNotFoundError will be raised.

w+ :-

  • Open the file for Reading and Writing
  • If file exist, File will be opened and all data will be erased,
  • If file does not exist, then new file will be created
  • In the beginning file pointer will point to 0 (as there is not data)
  • Now if you want to write something, then write
  • File pointer will be Now pointing to end of file (after write process)
  • If you want to read the data now, seek to specific point. (for beginning seek(0))

So, Overall saying both are meant to open the file to read and write but difference is whether we want to erase the data in the beginning and then do read/write or just start as it is.

abc.txt - in beginning

1234567
abcdefg
0987654
1234

Code for r+

with open('abc.txt', 'r+') as f:      # abc.txt should exist before opening
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0
567
abcdefg
0987654
1234

abc.txt - After Run:

abcd567
abcdefg
0987654
1234Sunny

Resetting abc.txt as initial

Code for w+

with open('abc.txt', 'w+') as f:     
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0


abc.txt - After Run:

abcdSunny
2

The file is truncated, so you can call read() (no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

Elazar
  • 20,415
  • 4
  • 46
  • 67
2

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

Dory Zidon
  • 10,497
  • 2
  • 25
  • 39
2

Actually, there's something wrong about all the other answers about r+ mode.

test.in file's content:

hello1
ok2
byebye3

And the py script's :

with open("test.in", 'r+')as f:
    f.readline()
    f.write("addition")

Execute it and the test.in's content will be changed to :

hello1
ok2
byebye3
addition

However, when we modify the script to :

with open("test.in", 'r+')as f:
    f.write("addition")

the test.in also do the respond:

additionk2
byebye3

So, the r+ mode will allow us to cover the content from the beginning if we did't do the read operation. And if we do some read operation, f.write()will just append to the file.

By the way, if we f.seek(0,0) before f.write(write_content), the write_content will cover them from the positon(0,0).

Find
  • 75
  • 1
  • 12
1

Here is the list might be helpful

Character Meaning

'r' - open for reading (default)

'w' - open for writing, truncating the file first

'x' - open for exclusive creation, failing if the file already exists

'a' - open for writing, appending to the end of the file if it exists

'b' - binary mode

't' - text mode (default)

'+' - open for updating (reading and writing)

The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation.

Reference:https://docs.python.org/3/library/functions.html#open

SSV 1
  • 35
  • 7
1

I was sooo confusing too... But may be my answer will help someone. I assume that you want to leverage the ability of 'w+' mode to create the file if it doesn't exist.

Indeed, only w, w+, a, a+ can create if the file doesn't exist.

But if you need to read the data of the file (the scenario when the file with data did exist) you can't do it with w+ out of the box because it truncates the file. Oops, you didn't mean that!

So, probably, your best friend would be a+ with file.seek(0):

with open('somefile.txt', 'a+') as f:
    f.seek(0)
    for line in f:
        print(f.readline())
Andrew Anderson
  • 1,044
  • 3
  • 17
  • 26
0

As mentioned by h4z3, For a practical use, Sometimes your data is too big to directly load everything, or you have a generator, or real-time incoming data, you could use w+ to store in a file and read later.

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59