Python open()
is a built-in function that opens a file and returns the corresponding file object. If the file cannot be opened OSError
is raised.
f = open(file_name, access_mode)
Where,
(r)
if not specified explicitly. Here is the list of different modes in which a file can be opened.Mode | Description |
---|---|
r | Opens a file for reading mode only. |
w | Opens a file for writing mode only. Creates a new file for writing it the file doesn’t exist. |
rb | Opens a binary file for reading mode only. |
wb | Opens a binary file for writing mode only. Creates a new file for writing it the file doesn’t exist. |
r+ | Opens a file for reading and writing mode. |
rb+ | Opens a binary file for reading and writing mode. |
w+ | Opens a file for writing and reading mode. Creates a new file for writing it the file doesn’t exist. |
wb+ | Opens a binary file for writing and reading mode. Creates a new file for writing it the file doesn’t exist. |
a | Opens a file for appending. Creates a new file for writing it the file doesn’t exist. |
a+ | Opens a file for appending and reading. Creates a new file for reading and writing it the file doesn’t exist. |
ab | Opens a binary file for appending. Creates a new file for writing it the file doesn’t exist. |
ab+ | Opens a binary file for reading and writing mode. Creates a new file for reading and writing it the file doesn’t exist. |
Recommended reading: Python Files I/O (File Handling In Python)
Let’s create a text file example.txt
and save it in our working directory.
Now here is the code to open the file using Python open().
f = open('example.txt','r') #open file from working directory in reading mode
fp = open('C:/xyz.txt','r') #open file from any directory
In above example, f
is a pointer variable pointing to the file example.txt
.
To print the content of and details of example.txt
, here is the code.
>>> print (*f) #print the content of file
This is a text file.
>>> print (f) #ptint mode and encoding
<_io.TextIOWrapper name='example.txt' mode='r' encoding='cp1252'>
Note that the default encoding in Windows is cp1252
whereas in Linux default encoding is utf-08
.