Python is a very handy programming language. Its easy syntax and built-in functions come in very useful when a programmer deals with the data flow. Apart from Python's powerful frameworks and libraries, the inbuilt Python file handling system itself provides an elegant and efficient way to write and read data between a file.
For example, if you have a text file with some data such as student names, a story, or any confidential or random data, you can easily access that text data in python and perform data crunching or data analysis. The reading data from a text file comes under Python file handling. Not only can you read data from the file, but you also write and append new data into the file. But in the tutorial, we will only be exploring the basic read from a file feature of Python.
To read from a file, you just require Python installed in your system and the file from which you want to read the data. So let's get started.
Step 1 Open The File
The first step toward reading the file using Python is to open the file in your Python program, so your Python program can read it. The concept is pretty similar to reading a book. When we want to read a book, we first need to open it, the same case goes for Python programming. To open a file in Python, we use Python's
open()
function.
syntax
open(fileName, 'r')
The
fileName
represents the full path to the file. And
'r'
specifies that open the file in reading mode.
Example
# if the data.txt file in the same directory of Python script
filename = 'data.txt'
open(filename, 'r')
The Above example will open the
data.txt
file in reading mode. We only need to specify the file name with its extension if the file is present in the same directory of the Python program. If the Python program and file are present in different directories, we need to specify the absolute or relative path for the
data.txt
file.
Example
filename = 'C:\Users\tsmehra\Desktop\code\data.txt'
file_obj = open(filename, 'r')
The open function returns a file object, which we can later use to access the text data of the
data.txt
file. There is an alternative and more professional way to open a file, using context manager. The context manager provides an error-free approach to dealing with file handling in Python. Using the
with
keyword with
open()
function, we can open the file in any mode and structure our data accessing.
Syntax
with open(filename, 'r') as file_obj:
.......
Example
filename ='data.txt'
with open(filename, 'r') as file_obj:
Similar to the previous syntax, when we use a context manager
with
to open a file, we create a file object. In both cases, with context manage or without context manager, we create a file object using the
open()
function.
Step 2 Python Read File
After opening the file, now it's time to read the data. Python support 3 functions that can read the data from the file. All these three functions are actually methods that can be called using the file object generated during file opening.
-
read(): The
read
function returns all the data of the file at once in string. -
readline(): The
readline
function returns a new line of data with each iteration of the loop. -
readlines(): The
readlines
method returns a list of all lines present in the file.
Now let's go through all these functions or methods one by one
Python read() function
The Python
read()
is a file object method that reads all the file data at once and returns it as a string. This method comes in very useful when we want to read all the data at once.
Example
# open file in read mode
with open('data.txt', 'r') as file_obj:
# read all data at once
all_data = file_obj.read()
# print all data
print(all_data)
Output
Far far away, behind the word mountains, far from the countries Vokalia and Consonantia,
there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the
Semantics, a large language ocean.
A small river named Duden flows by their place and supplies it with the necessary regelialia.
It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
Even the all-powerful Pointing has no control about the blind texts it is an almost
unorthographic life One day however a small line of blind text by the name of Lorem Ipsum
decided to leave for the far World of Grammar.
Once we have all the data from
read()
method, we can analyze the data character by character and perform various functions. Let's say we do not want to print the vowels present in the
data.txt
file,
# open file in read mode
with open('data.txt', 'r') as file_obj:
# read all data at once
all_data = file_obj.read()
for char in all_data:
# check if the chracter is not vowel
# print it
if not char.lower() in 'aeiou':
print(char, end="")
Output
Fr fr wy, bhnd th wrd mntns, fr frm th cntrs Vkl nd Cnsnnt, thr lv th blnd txts. Sprtd thy lv n Bkmrksgrv rght t th cst f th Smntcs, lrg lngg cn.
smll rvr nmd Ddn flws by thr plc nd sppls t wth th ncssry rgll. t s prdsmtc cntry, n whch rstd prts f sntncs fly nt yr mth.
vn th ll-pwrfl Pntng hs n cntrl bt th blnd txts t s n lmst nrthgrphc lf n dy hwvr smll ln f blnd txt by th nm f Lrm psm dcdd t lv fr th fr Wrld f Grmmr.
The above program will print all the text from the data.txt file except for the vowels.
Python readline () function
Let's say you want to read the file data line by line, one line at a time. In that case, you can use the
readline()
method. The
readline()
method return a single line of the file, one by one. If a file contains only 3 lines (like our file), we can only call
readline()
method three times, and every time it gets called, it will return a new line from the file. And after the third line, it will start to return an empty string.
Example
# open file in read mode
with open('data.txt', 'r') as file_obj:
# print line 1
print("Line 1")
print(file_obj.readline())
# print line 2
print("Line 2")
print(file_obj.readline())
# print line 3
print("Line 3")
print(file_obj.readline())
Output
Line 1
Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.
Line 2
A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
Line 3
Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
The readline() method also add a line break '\n' at the end of the returned line string.
Python readlines() function
The Python readlines() method is quite similar to the
readline()
method. The only difference is, the
readlines()
method returns a Python list of all lines present in the file at once. For most of cases, you will be using the readlines() method when you want to read a file line by line because it provides a better way to read the exact line of a file.
Example
# open file in read mode
with open('data.txt', 'r') as file_obj:
# access all lines
all_lines = file_obj.readlines()
print(all_lines)
Output
['Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.\n', 'A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth.\n', 'Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar.']
Conclusion
To read a file we first need to open the file, and in doing so, we generate a Python file object that supports many inbuilt functions to read data from the file. With standard python practice, developers generally use Python context manager to open and deal with file handling, as we have demonstrated in the above example. To read the complete data at once, we can use the Python read function, and to read the data line by line, we can either use the readline() or readlines() functions.
People are also reading:
- What is a constructor in Python?
- How to Play sounds in Python?
- Python SyntaxError: unexpected EOF while parsing Solution
- Python vs PHP
- Python typeerror: ‘int’ object is not subscriptable Solution
- Java vs Python
- Python typeerror: list indices must be integers or slices, not str Solution
- Python ‘numpy.ndarray’ object is not callable Solution
- Python vs Django
- Python SyntaxError: can’t assign to function call Solution
Leave a Comment on this Post