Python Program to read a file line by line and print it on the console
Basic File IO in Python
open()
The open()
function takes multiple arguments.
First being a positional string parameter representing the path to the file that should be opened.
The second optional parameter is also a string which specifies the mode of interaction you intend for the file object being returned by the function call. By default, it will be opened in reading mode.
close()
Once you have written or read all of the desired data for a file object you need to close the file so that resources can be reallocated on the operating system that the code is running on fp.close()
An alternative and safer way to close all the objects pointed by file pointer of the opened file is:
try: fp = open(‘path/to/file.txt’) # do stuff here finally:
fp.close()
Reading Line by Line
The file object returned from open()
has three common explicit methods (read
, readline
, and readlines
) to read in data and one more implicit way.
The read
the method will read in all the data into one text string. This is useful for smaller files where you would like to do text manipulation on the entire file, or whatever else suits you. Then there is readline
which is one useful way to only read in individual line incremental amounts at a time and return them as strings. The last explicit method, readlines
will read all the lines of a file and return them as a list of strings.
One elegant way of reading in a file line-by-line includes iterating over a file object in a for
loop assigning each line to a special variable called line
. The count of the line is also displayed.
try:
filepath = ''# path to file seperated by //
with open(filepath) as fp:
for cnt, line in enumerate(fp):
print("Line {}: {}".format(cnt, line))
finally:
fp.close()
If you want only the contents of the file and not the line number then,
try:
filepath = ''# path to file seperated by //
with open(filepath) as fp:
for cnt,line in enumerate(fp):
print("{}".format(line))
finally:
fp.close()
In the above two implementations, we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for
loop in the combination of using the iterable object fp
. Not only is this simpler to read but it also takes fewer lines of code to write, which is always a best practice.