The open()
function helps to load files from the system hard drive to volatile memory. By definition, it takes multiple argument values, but in this shot, we'll only elaborate on path
and mode
arguments. Multiple built-in methods are available to read file content including read()
, readlines()
, and readline()
.
open(path, mode)
path
: This represents a string or path-like object which is used to specify a file that is to be loaded.mode
: This indicates the mode or rule by which the file will be loaded to running memory. Here, we have a list of different types of modes.Mode | Description |
| Opens a file in both read and write mode |
| Opens file for reading only |
| Opens file for writing only |
| Opens file in exclusive creation mode |
| Opens file in append mode. It does not allow to truncate and create a new file by default if does not exist |
| Opens file in text mode |
| Opens file in binary mode |
Now, let's elaborate on how to read any file in Python using a pre-defined open()
function. To do that, we need to pass the file name employee.txt
as the first argument with the reading mode 'r'
as the second argument value.
fd = open('employee.txt','r')
The open('employee.txt','r')
loads the employee.txt
file in reading mode and returns a file descriptor fd
. This file object allows us to interact with the content of the file.
content = fd.read()
The fd.read()
reads all text of the file and returns it as a single string object. We can also use fd.readline()
or fd.readlines()
according to our needs.
fd.readline()
: This returns every line of the file as a definite string.fd.readlines()
: This reads all lines of the file as strings but returns a list of strings.fd.close()
When we complete our work, it's mandatory to call the close()
method to release occupied system resources by loaded file. It demonstrates that we have meticulously performed our obligations on file.
fd = open('employee.txt','r')content = fd.read()print(content)fd.close()
main.py
fileprint(content)
prints the contents of a file to a console.
employee.txt
fileThis file contains a record of three individuals including their names, designation, salary, and many more.