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