Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • 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:
How to Read from a File in Python
Next article icon

How to Read from a File in Python

Last Updated : 13 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.txt

Hello World
Hello GeeksforGeeks

Basic File Reading in Python

Basic file reading involves opening a file, reading its contents, and closing it properly to free up system resources.

Steps:

  • Open the file: open("filename", "mode") opens the file in a specified mode (e.g., read mode "r").
  • Read content: Using read(), readline() or readlines() methods.
  • Close the file: close() ensures system resources are released.

Example: Reading the Entire File

Python
# Open the file in read mode
file = open("geeks.txt", "r")

# Read the entire content of the file
content = file.read()

print(content)

# Close the file
file.close()

Output:

Hello World
Hello GeeksforGeeks

Explanation: This code opens geeks.txt in read mode, reads all its content into a string, prints it and then closes the file to free resources.

Best Practice: Using with statement

Using with open(...) ensures the file is automatically closed.

Python
with open("geeks.txt", "r") as file:
    content = file.read()
    print(content)
Hello World 
Hello GeeksforGeeks

Explanation: This code ensures that the file is automatically closed once the block is exited, preventing resource leaks.

Table of Content

  • Reading a File Line by Line
  • Reading Binary Files in Python
  • Reading Specific Parts of a File
  • Reading CSV Files in Python
  • Reading JSON Files in Python

Reading a File Line by Line

We may want to read a file line by line, especially for large files where reading the entire content at once is not practical. It is done with following two methods:

  • for line in file: Iterates over each line in the file.
  • line.strip(): Removes any leading or trailing whitespace, including newline characters.

Example 1: Using a Loop to Read Line by Line

Python
# Open the file in read mode
file = open("geeks.txt", "r")

# Read each line one by one
for line in file:
    print(line.strip())  # .strip() to remove newline characters

# Close the file
file.close()

Output:

Hello World
Hello GeeksforGeeks

Explanation: This method reads each line of the file one at a time and prints it after removing leading/trailing whitespace.

Example 2: Using readline()

file.readline() reads one line at a time. while line continues until there are no more lines to read.

Python
# Open the file in read mode
file = open("geeks.txt", "r")

# Read the first line
line = file.readline()

while line:
    print(line.strip())
    line = file.readline()  # Read the next line

# Close the file
file.close()

Output:

Hello World
Hello GeeksforGeeks

Explanation: This method reads a single line at a time using readline(), which is useful when processing files in chunks.

Reading Binary Files in Python

Binary files store data in a format not meant to be read as text. These can include images, executables or any non-text data. We are using following methods to read binary files:

  • open("example.bin", "rb"): Opens the file example.bin in read binary mode.
  • file.read(): Reads the entire content of the file as bytes.
  • file.close(): Closes the file to free up system resources.

Example: Reading a Binary File

Python
# Open the binary file in read binary mode
file = open("geeks.txt", "rb")

# Read the entire content of the file
content = file.read()

# Print the content (this will be in bytes)
print(content)

# Close the file
file.close()

Output:

b'Hello World\r\nHello GeeksforGeeks'

Explanation: This code reads a file in binary mode ("rb") and prints its content as bytes, which is necessary for handling non-text files.

Reading Specific Parts of a File

Sometimes, we may only need to read a specific part of a file, such as the first few bytes, a specific line, or a range of lines. Example: Reading the First N Bytes

Python
# Open the file in read mode
file = open("geeks.txt", "r")

# Read the first 10 bytes
content = file.read(10)

print(content)

# Close the file
file.close()

Output:

Hello World

Explanation: This code reads only the first 10 characters of the file, useful for previewing file contents.

Reading CSV Files in Python

Reading CSV (Comma-Separated Values) files are a common task for working with tabular data. Python's csv module makes it easy to read CSV files. Example:

Python
import csv

# Open the CSV file
with open("example.csv", newline='') as csvfile:
   
    # Create a CSV reader object
    csvreader = csv.reader(csvfile)
    
    # Read and print each row
    for row in csvreader:
        print(row)

Output:

['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Dollars', 'H34', 'Total income per employee count', 'Financial ratios', '769,400', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Dollars', 'H35', 'Surplus per employee count', 'Financial ratios', '48,000', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H36', 'Current ratio', 'Financial ratios', 'C', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H37', 'Quick ratio', 'Financial ratios', 'C', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H38', 'Margin on sales of goods for resale', 'Financial ratios', '12', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H39', 'Return on equity', 'Financial ratios', '19', 'ANZSIC06 groups C211, C212, C213 and C214']

Explanation: This code reads a CSV file line by line, parsing it into a list of values for each row.

Reading JSON Files in Python

Reading JSON (JavaScript Object Notation) files are widely used for data interchange. Python's json module provides methods to read JSON files. Example:

Python
import json

# Open the JSON file
with open("sample1.json", "r") as jsonfile:
    
    # Load the JSON data
    data = json.load(jsonfile)
    print(data)

Output:

{'fruit': 'Apple', 'size': 'Large', 'color': 'Red'}

Explanation: This code reads a JSON file and loads its content into a Python dictionary, which can be used for further processing.


Next Article
How to Read from a File in Python

N

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

Similar Reads

    How to read Dictionary from File in Python?
    In Python, reading a dictionary from a file involves retrieving stored data and converting it back into a dictionary format. Depending on how the dictionary was saved—whether as text, JSON, or binary-different methods can be used to read and reconstruct the dictionary for further use in your program
    3 min read
    How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
    How to read specific lines from a File in Python?
    Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers
    3 min read
    How to delete data from file in Python
    When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data.For more on file handling, check out:File Handling in Pyt
    3 min read
    How to get file size in Python?
    We can follow different approaches to get the file size in Python. It's important to get the file size in Python to monitor file size or in case of ordering files in the directory according to file size.  Method 1: Using getsize function of os.path module This function takes a file path as an argume
    3 min read
    Read File As String in Python
    Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
    3 min read
    How to remove blank lines from a .txt file in Python
    Many times we face the problem where we need to remove blank lines or empty spaces in lines between our text to make it look more structured, concise, and organized. This article is going to cover two different methods to remove those blank lines from a .txt file using Python code. This is going to
    3 min read
    How to search a pickle file in Python?
    Prerequisites: pickle file  Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to conver
    3 min read
    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
    How to read large text files in Python?
    In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python.  To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates
    3 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.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

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