• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Read File Line by Line in Python

Read File Line by Line in Python

Author: Aditya Raj
Last Updated: August 8, 2022

File operations are crucial during various tasks. In this article, we will discuss how we can read a file line by line in python.

Read File Using the readline() Method

Python provides us with the readline() method to read a file. To read the file, we will first open the file using the open() function in the read mode. The open() function takes the file name as the first input argument and the literal “r” as the second input argument to denote that the file is opened in the read mode. After execution, it returns a file object containing the file.

After getting the file object, we can use the readline() method to read the file. The readline() method, when invoked on a file object, returns the current unread line in the file and moves the iterator to next line in the file. 

To read the file line by line, we will read the each line in the file using the readline() method and print it in a while loop. Once the readline() method reaches the end of the file, it returns an empty string. Hence, in the while loop, we will also check if the content read from the file is an empty string or not,if yes, we will break out from the for loop. 

The python program to read the file using the readline() method is follows.

myFile = open('sample.txt', 'r')
print("The content of the file is:")
while True:
    text = myFile.readline()
    if text == "":
        break
    print(text, end="")
myFile.close()

Output:

The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.

Suggested Article: Upload File to SFTP Server using C# | DotNet Core | SSH.NET

Read File Line by Line in Python Using the readlines() Method

Instead of the readline() method, we can use the readlines() method to read a file in python. The readlines() method, when invoked on a file object, returns a list of strings, where each element in the list is a line from the file. 

After opening the file, we can use the readlines() method to get a list of all the lines in the file. After that, we can use a for loop to print all the lines in the file one by one as follows.

myFile = open('sample.txt', 'r')
print("The content of the file is:")
lines = myFile.readlines()
for text in lines:
    print(text, end="")
myFile.close()

Output:

The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.

Conclusion

In this article, we have discussed two ways to read a file line by line in python. To learn more about programming in python, you can read this article on list comprehension in Python. You might also like this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us