Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Read a file line by line in Python
Next article icon

Read a file line by line in Python

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file.

Example:

Python
with open('filename.txt', 'r') as file:     for line in file:         print(line.strip()) 

Using Loop

An iterable object is returned by open() function while opening a file. This final way of reading a file line-by-line includes iterating over a file object in a loop. In doing this 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 combination with using the iterable object.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]  file1 = open('myfile.txt', 'w') file1.writelines(L) file1.close()  file1 = open('myfile.txt', 'r') count = 0  print("Using for loop") for line in file1:     count += 1     print("Line{}: {}".format(count, line.strip()))  file1.close() 

Output

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks

Using List Comprehension

A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Here, we will read the text file and print the raw data including the new line character in another output we removed all the new line characters from the list.

Python
with open('myfile.txt') as f:     l = [line for line in f]  print(l)  with open('myfile.txt') as f:     l = [line.rstrip() for line in f]  print(l) 

Output:

['Geeks\n', 'For\n', 'Geeks']
['Geeks', 'For', 'Geeks']

Using readlines()

Python readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline '\n' character using strip() function.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]  file1 = open('myfile.txt', 'w') file1.writelines(L) file1.close()  file1 = open('myfile.txt', 'r') Lines = file1.readlines()  count = 0 for line in Lines:     count += 1     print("Line{}: {}".format(count, line.strip())) 

Output

Line1: Geeks
Line2: for
Line3: Geeks

Python With Statement

When working with files in Python, it is important to close the file after operations to avoid bugs such as unsaved changes or resource leaks. Normally, you would need to explicitly call file.close() after opening a file.

However, using the with statement simplifies this process. It automatically handles opening and closing the file for you, ensuring the file is properly closed as soon as the code block inside the with statement finishes execution even if an error occurs. This eliminates the need to manually close the file and results in cleaner, safer code.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]  with open("myfile.txt", "w") as fp:     fp.writelines(L)  count = 0 print("Using readlines()")  with open("myfile.txt") as fp:     l = fp.readlines()     for line in l:         count += 1         print("Line{}: {}".format(count, line.strip()))  count = 0 print("\nUsing readline()")  with open("myfile.txt") as fp:     while True:         count += 1         line = fp.readline()          if not line:             break         print("Line{}: {}".format(count, line.strip()))  count = 0 print("\nUsing for loop")  with open("myfile.txt") as fp:     for line in fp:         count += 1         print("Line{}: {}".format(count, line.strip())) 

Output

Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks

Using readline()
Line1: Geeks
Line2: for
Line3: Geeks

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks

Next Article
Read a file line by line in Python

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • python-file-handling
Practice Tags :
  • python

Similar Reads

    Read a file without newlines in Python
    When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file wi
    2 min read
    fileinput.lineno() in Python
    With the help of fileinput.lineno() method, we can get the line number for every line on line read from input file by using fileinput.lineno() method. Syntax : fileinput.lineno() Return : Return the line number. Example #1 : In this example we can see that by using fileinput.lineno() method, we are
    1 min read
    How to Read from a File in Python
    Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently.Example File: geeks.txtHello World Hello GeeksforGe
    5 min read
    Open a File in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, each line of text is terminated with a special character called EOL
    6 min read
    Reading binary files in Python
    Reading binary files means reading data that is stored in a binary format, which is not human-readable. Unlike text files, which store data as readable characters, binary files store data as raw bytes. Binary files store data as a sequence of bytes. Each byte can represent a wide range of values, fr
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences