How to Read from a File in Python
Last Updated :
13 Mar, 2025
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.
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read