The Wayback Machine - https://web.archive.org/web/20250126175012/https://www.geeksforgeeks.org/how-to-read-from-a-file-in-python/
Open In App

How to Read from a File in Python

Last Updated : 19 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Basic File Reading in Python

Basic file reading involves opening a file and reading its contents into your program. This can be done using the following built-in open() functions.

  • open(“geeks.txt”, “r”): Opens the file example.txt in read mode.
  • file.read(): Reads the entire content of the file.
  • file.close(): Closes the file to free up system resources.

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 the content
print(content)
# Close the file
file.close()

Output:

Hello World
Hello GeeksforGeeks

Line-by-Line Reading in Python

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

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

Reading Binary Files in Python

Binary files store data in a format not meant to be read as text. These can include images, executablesor 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'

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

file.read(10): Reads the first 10 bytes of the file.

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: Using the csv Module

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

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: Using the json Module

Python
import json

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

Output:

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


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg