Reading files is a common task in Python. It allows programs to access data stored in files, such as text files, logs, configuration files, or datasets.

Python provides built-in functions to open and read files easily.


πŸ“– Opening a File

To read a file, you must first open it using the open() function.

Syntax:

file = open("filename", "mode")
  • filename β†’ name of the file
  • mode β†’ how the file will be used

For reading files, the mode is "r".

Example:

file = open("data.txt", "r")

πŸ“„ Reading the Entire File

The read() method reads the entire content of a file.

Example:

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

πŸ“‘ Reading Line by Line

The readline() method reads one line at a time.

Example:

file = open("data.txt", "r")

line = file.readline()
print(line)file.close()

To read multiple lines:

file = open("data.txt", "r")

print(file.readline())
print(file.readline())file.close()

πŸ“‹ Reading All Lines as a List

The readlines() method reads all lines and stores them in a list.

Example:

file = open("data.txt", "r")

lines = file.readlines()
print(lines)file.close()

Output example:

['Hello\n', 'Welcome to Python\n', 'File Handling\n']

πŸ” Reading Files Using a Loop

A common way to read files is using a for loop.

Example:

file = open("data.txt", "r")

for line in file:
print(line)file.close()

βœ… Using with open() (Recommended)

The with statement automatically closes the file after reading.

Example:

with open("data.txt", "r") as file:
content = file.read()
print(content)

Advantages:

βœ” Automatically closes the file
βœ” Cleaner and safer code


πŸ“ Example File

Suppose data.txt contains:

Hello
Python Programming
File Handling Example

Python code:

with open("data.txt", "r") as file:
for line in file:
print(line)

Output:

Hello
Python Programming
File Handling Example

🧠 File Reading Modes

ModeDescription
rRead file (default)
rbRead binary file
r+Read and write

🧾 Summary

Python provides several ways to read files:

  • read() β†’ reads entire file
  • readline() β†’ reads one line
  • readlines() β†’ reads all lines into a list
  • with open() β†’ safest way to handle files