Reading a file line by line in Python
In this article we will discuss different ways to read a file line by line in Python. In Python, there is no need for importing external library for file handling. Learn how to create, open, append, read, read line by line and Write.
Opening a file and reading the content of a file is a common thing in software development these days. Let’s have a look at various ways of reading files in Python.
Reading a file
f = open("pcode.txt", "r") filecontent = f.read() f.close()
Here the read() method reads the entire content of the file.
To read only a specific part of a file, we can make use of the arguments for read().
f = open("pcode.txt", "r") filecontent = f.read(10) f.close()
The above snippet reads only the first ten characters of the file pcode.txt.
Reading a file line by line
An easy way to read each line in a file is to use the python statement using readline() method on an object.
f = open("pcode.txt", "r") filecontent = f.readline() f.close()
This returns the first line of the file only.
To read all the lines one by one, we can loop and read.
f = open("pcode.txt", "r") #read first file lines = f.readline() #read till end of the file while lines: lines = f.readline() f.close()
There’s one more way to read a file line by line, but this alternative works only with text files
f = open("pcode.txt", "r") for line in f: print(line) fh.close()
Reading all lines at once
The readlines() method reads until EOF using readline() and returns a list containing all the lines.
f = open("pcode.txt", "r") filecontent = f.readlines() f.close()
File Modes
The open function on a file object needs two arguments to work with. The first one is the file name and the second one is the mode depending upon which the file would be opened.
r – Default mode. Opens file for reading.
w – Opens file for writing. If file doesn’t exist, it creates a new file. If file exists it truncates the file.
x – Creates a new file. If file already exists, the operation fails.
a – Open file in append mode. If file does not exist, it creates a new file.
t – This is the default mode for format. It opens in text mode.
b – This opens in binary mode
+ – This will open a file for updating a file