Read File
Last Updated : 5th September 2025
Read a file means to read the content of a file.It can we done using following methods.
1. read()
It read the entire content of the file and returns it as a string.It take an optional parameter that specifies the number of characters to read from the file.
file = open("example.txt", "r")
content = file.read()
file.close()
file = open("example.txt", "r")
content = file.read(10) # Read the first 10 characters
file.close()
2. readline()
It reads a single line from the file and returns it as a string.
file = open("example.txt", "r")
line = file.readline()
file.close()
3. readlines()
It reads all the lines of the file and returns them as a list of strings.You can pass an optional parameter that specifies the number of lines to read from the file.
file = open("example.txt", "r")
lines = file.readlines()
file.close()
file = open("example.txt", "r")
lines = file.readlines(2) # Read the first 2 lines
file.close()
with open("students.csv", "r") as f:
data = f.readlines()
for line in data[1:]: # skip header
name, score = line.strip().split(",")
print(f"{name} scored {score}")