- How to read File Line by Line in Python?
- Example 1: Read Text File Line by Line – readline()
- Example 2: Read Lines as List – readlines()
- Example 3: Read File Line by Line using File Object
- Summary
- How to Read a File line by line in Python? (with code)
- How to Read a .txt File in Python?
- How to read a Text File line-by-line in Python?
- How to Read a File into a List?
- Conclusion
How to read File Line by Line in Python?
There are many ways to read a text file line by line in Python. You can read the lines to a list, or just access them one by one in a loop by iterating over the lines provided by some kind of iterator or calling a function on the file object.
In this tutorial, we will learn how to read a file line by line using readline() function, readlines() function, or file object, with the help of example programs.
Example 1: Read Text File Line by Line – readline()
In this example, we will use readline() function on the file stream to get next line in a loop.
Steps to use file.readline() function
Following are the steps to read file line by line using readline() function.
- Read file in text mode. It returns a stream to the file.
- Create an Infinite While Loop.
- During each iteration of the loop, read the next line from the file using readline().
- If the line is not empty, you have the next line. You can check this using if-not. Else, there are no more lines in the file, and we break the loop.
Python Program
#get file object file1 = open("sample.txt", "r") while(True): #read next line line = file1.readline() #check if line is not null if not line: break #you can access the line print(line.strip()) #close file file1.close
Hi User! Welcome to Python Examples. Continue Exploring.
Example 2: Read Lines as List – readlines()
readlines() function returns all the lines in the file as a list of strings. We can traverse through the list, and access each line of the file.
In the following program, we shall read a text file, and then get the list of all lines in the text file using readlines() function. After that, we use For Loop to traverse these list of strings.
Python Program
#get file object file1 = open("sample.txt", "r") #read all lines lines = file1.readlines() #traverse through lines one by one for line in lines: print(line.strip()) #close file file1.close
Hi User! Welcome to Python Examples. Continue Exploring.
Example 3: Read File Line by Line using File Object
In our first example, we have read each line of file using an infinite while loop and readline() function. But, you can use For Loop statement on the file object itself to get the next line in the file in each iteration, until the end of file.
Following is the program, demonstrating how we use for-in statement to iterate over lines in the file.
Python Program
#get file object file1 = open("sample.txt", "r") #traverse through lines one by one for line in file1: print(line.strip()) #close file file1.close
Hi User! Welcome to Python Examples. Continue Exploring.
Summary
In this tutorial of Python Examples, we learned how to read a text file line by line, with the help of well detailed python example programs.
How to Read a File line by line in Python? (with code)
Python is a robust programming language with built-in support for reading and writing files. In this article, we’ll go over the various approaches to reading a text file line-by-line in Python. But first we have to revise some concepts about reading text files in general.
How to Read a .txt File in Python?
We need text files for many reasons and so, each coder should know how to operate them. We use the open() function to read a text file in Python. This function is used to open a file and returns a file object. It can have two arguments: the file name or path and the mode in which to open the file. Here is the simple syntax for this operation.
Here ‘example.txt’ is the file name that we want to open, and ‘r’ is the mode that signifies that we want to read the file.
The other modes available are as follows:
- Read Mode (‘r’): It simply reads the contents of a file.
- Write Mode (‘w’): If your file already exists, this will overwrite the content of your file. Otherwise creates a new file.
- Append Mode (‘a’): It appends the content in an already existing file instead of overwriting, If a file does not exist It creates a new file.
Now that we have a fundamental understanding of how to open and operate a file, Here is a simple example:
file = open('example.txt', 'r') read_=file.read() print(read_)
Python is a high-level, interpreted programming language that is popular among developers for its simplicity, readability, and flexibility. It was first released in 1991 by Guido van Rossum and has since become one of the most widely used programming languages in the world. Python is often used for web development, scientific computing, data analysis, artificial intelligence, and machine learning. One of the main advantages of Python is its large and active community, which has created a vast number of libraries and frameworks that make it easy to get started and build complex applications quickly.
A demo file called «example.txt» that contains some text about Python was created, and its contents were read using the read() function. As you can see, the output includes the entire content.
How to read a Text File line-by-line in Python?
Sometimes, reading a text file is not enough and we need to separate each line in the content of the file, so we have a great function by Python for this purpose.
We can read the file line by line in Python using a while loop and the readline() function. With the readlin() function called on the file, we read each single line of text, storing it in the line variable. We end the loop if the line variable is empty because that indicates that the file has ended. If not, the line is printed.
file = open('example.txt', 'r') while True: line = file.readline() if not line: break print(line)
Python is a high-level, interpreted programming language that is popular among developers for its simplicity, readability, and flexibility. It was first released in 1991 by Guido van Rossum and has since become one of the most widely used programming languages in the world. Python is often used for web development, scientific computing, data analysis, artificial intelligence, and machine learning. One of the main advantages of Python is its large and active community, which has created a vast number of libraries and frameworks that make it easy to get started and build complex applications quickly.
Please keep in mind that this function keeps track of its current position in the file. That’s why we need a loop to iterate over the file and read the next line of text from the file.
The key distinction between the two approaches is that the read() function reads the entire file in a single pass and disregards any available sentence spaces, whereas the readline() function reads a single line in a single pass, from the first character to the next available sentence space, prints it, and repeats the process.
However, you should also know about the readlines() method. With the help of this, we can quickly read every line in a text file while maintaining the sentence breaks. The readlines() functions reads every line and stores it in the variable lines in this case. Then, display each line after iterating through the lines using a «for» loop.
file = open('example.txt', 'r') lines = file.readlines() for line in lines: print(line)
Python is a high-level, interpreted programming language that is popular among developers for its simplicity, readability, and flexibility. It was first released in 1991 by Guido van Rossum and has since become one of the most widely used programming languages in the world. Python is often used for web development, scientific computing, data analysis, artificial intelligence, and machine learning. One of the main advantages of Python is its large and active community, which has created a vast number of libraries and frameworks that make it easy to get started and build complex applications quickly.
How it works is that the entire file is read into memory as a list of strings, which can be inefficient for large files. So, it is more memory-efficient to use a loop with the readline() method.
How to Read a File into a List?
What is actually happening here is that Python is maintaining a list with every line of the file’s content as an element, and then using the ‘for’ loop we iterate over the list to print individual lines. As you can see in the previous method, readlines() stores all the lines in a variable. Therefore, we can simply print the list variable if we want a list of the information. For Example:
file = open('example.txt', 'r') lines = file.readlines() print(lines)
['Python is a high-level, interpreted programming language that is popular among developers for its simplicity, readability, and flexibility. \n', 'It was first released in 1991 by Guido van Rossum and has since become one of the most widely used programming languages in the world.\n', 'Python is often used for web development, scientific computing, data analysis, artificial intelligence, and machine learning. \n', 'One of the main advantages of Python is its large and active community, which has created a vast number of libraries and frameworks that make it easy to get started and build complex applications quickly.']
There is an alternative method that uses the strip() function, as shown below:
with open('example.txt', 'r') as file: lines = [] for line in file: line = line.strip() lines.append(line) print(lines)
['Python is a high-level, interpreted programming language that is popular among developers for its simplicity, readability, and flexibility.', 'It was first released in 1991 by Guido van Rossum and has since become one of the most widely used programming languages in the world.', 'Python is often used for web development, scientific computing, data analysis, artificial intelligence, and machine learning.', 'One of the main advantages of Python is its large and active community, which has created a vast number of libraries and frameworks that make it easy to get started and build complex applications quickly.']
Using a «with» block, the code reads the contents of a file called «example.txt» in read-only mode (‘r’). The following step involves reading each line from the file, using the «strip()» method to eliminate any leading or trailing white space characters, and adding the resulting line to a list called «lines». The list of lines that were stripped is then printed.
Conclusion
It is very easy to read a line-by-line in Python using readline method that you learned above. If you have an assignment that is related to this problem, we provide assignment help in Python to assist you with that. Happy Learning:)