Read File in Python | File Handling in Python Programming

Read File: To fetch all the information or data written in a file we need to perform read operation on a file. There are three methods are available in python programming for reading file. These available methods are:

python-video-tutorials

How Many Ways are There to Read a File?

1). Using read() method.
2). Using readline() method().
3). Using readlines() method.

read-method(i). read(): In python programming, read() method is used to read only single character from a file. The read() method takes numeric value as a arguments. This numeric value defines that how many character should be read.
If we leave it blank then it will read all data from the file till last index.

Example 1 demonstrating the use of read() method without argument and example 2 demonstrating the use of read() method with argument passing.

Syntax:

#www.pythonlobby.com
f = open("file_name",'r')
f.read(n) #or f.read()


Example 1:
For read() method without argument.

read-method-in-python-file-handling

Explanation: We have opened our existing file named “test.txt” in ‘r’ mode. Using read() method we read the complete character and stored it in z variable. Later we print the information stored in our variable ‘z’.

Example 2: For read() method with argument.

read-method-in-python-file-handling-2

Explanation: We have opened our existing file named “test.txt” in ‘r’ mode. Using read() method we read the first 15 character and stored it in z variable. Later we print the information stored in our variable ‘z’.