Overview of modes to write into files¶
Let us go through the details related to the modes that are used to write data into files. Already we have seen r
which is default as well as w
. They are meant for read and write respectively.
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
r
is used for read andw
,a
,x
are used for write.- We can read or write either in binary or text mode. Unless specified, operations are performed in text mode.
- We need to combine
b
with read or write operations to perform read or write in binary mode.
Overwriting the existing file using w¶
If the file does not exists, it will create otherwise it will overwrite.
In [1]:
!rm data/overwrite.txt
In [2]:
file = open('data/overwrite.txt', 'w')
In [3]:
data = 'Writing in file - attempt 1'
In [4]:
len(data)
Out[4]:
27
In [5]:
file.write(data)
Out[5]:
27
In [6]:
file.close()
In [7]:
!cat data/overwrite.txt
Writing in file - attempt 1
In [8]:
file = open('data/overwrite.txt', 'w')
In [9]:
data = 'Writing in file - attempt 2'
In [10]:
file.write(data)
Out[10]:
27
In [11]:
file.close()
In [12]:
!cat data/overwrite.txt # Data is overwritten
Writing in file - attempt 2
Appending into existing file using a¶
If the file does not exists, it will create otherwise it will append.
In [13]:
!rm data/append.txt
In [14]:
file = open('data/append.txt', 'a')
In [15]:
data = 'Writing in file - attempt 1'
In [16]:
file.write(data)
Out[16]:
27
In [17]:
file.close()
In [18]:
!cat data/append.txt
Writing in file - attempt 1
In [19]:
file = open('data/append.txt', 'a')
In [20]:
data = 'Writing in file - attempt 2'
In [21]:
file.write(data)
Out[21]:
27
In [22]:
file.close()
In [23]:
!cat data/append.txt # Data is appended
Writing in file - attempt 1Writing in file - attempt 2
Write into file using x¶
If the file already exists, it will fail.
In [24]:
!rm data/new_file.txt
In [25]:
file = open('data/new_file.txt', 'x')
In [26]:
data = 'Writing in file - attempt 1'
In [27]:
file.write(data)
Out[27]:
27
In [28]:
file.close()
In [29]:
!cat data/new_file.txt
Writing in file - attempt 1
In [30]:
file = open('data/new_file.txt', 'x') # Fails, as the file already exists
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last) Input In [30], in <cell line: 1>() ----> 1 file = open('data/new_file.txt', 'x') FileExistsError: [Errno 17] File exists: 'data/new_file.txt'