How to Read from a File in Python (original) (raw)

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:

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

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:

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

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