File modes

suggest change

There are different modes you can open a file with, specified by the mode parameter. These include:

with open(filename, 'r') as f:
    f.read()
with open(filename, 'w') as f:
    f.write(filedata)
with open(filename, 'a') as f:
    f.write('\n' + newdata)

What r r+ w w+ a a+
Read
Write
Creates file
Erases file
Initial position start start start start end end

Python 3 added a new mode for exclusive creation so that you will not accidentally truncate or overwrite and existing file.

What x x+
Read
Write
Creates file
Erases file
Initial position start start start start end end

Allow one to write your file open code in a more pythonic manner:

try:
    with open("fname", "r") as fout:
        # Work with your open file
except FileExistsError:
    # Your error handling goes here

In Python 2 you would have done something like

import os.path
if os.path.isfile(fname):
    with open("fname", "w") as fout:
        # Work with your open file
else:
    # Your error handling goes here

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Files, Folders, I/O:
* File modes

Table Of Contents
2 Filter
3 List
7 Loops
15 Files, Folders, I/O
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve