-
Hajipur, Bihar, 844101
To read a file in Python, use the built-in open()
function with read mode ("r"
).
f = open("demo.txt", "r")
print(f.read())
f.close()
read()
– Read Entire Filef = open("demo.txt", "r")
print(f.read())
f.close()
✅ Reads all content of the file as a single string.
read(n)
– Read Specific Charactersf = open("demo.txt", "r")
print(f.read(10)) # Reads first 10 characters
f.close()
readline()
– Read One Linef = open("demo.txt", "r")
print(f.readline())
f.close()
✅ Use it again to read the next line.
readlines()
– Read All Lines into Listf = open("demo.txt", "r")
lines = f.readlines()
print(lines)
f.close()
✅ Each line becomes an item in the list.
f = open("demo.txt", "r")
for line in f:
print(line.strip())
f.close()
✅ Best way to read big files, one line at a time.
with
Statement (Best Practice)with open("demo.txt", "r") as f:
content = f.read()
print(content)
✅ Automatically closes the file after reading.
with open("image.jpg", "rb") as file:
data = file.read()
Each read()
or readline()
moves the pointer forward.
Q1. Write a Python program to read and print all contents from sample.txt
.
Q2. Write a Python program to read only the first 20 characters of a file using read(20)
.
Q3. Write a Python program to use readline()
to read one line at a time from a file.
Q4. Write a Python program to loop through all lines in a file and print them using a for
loop.
Q5. Write a Python program to read all lines using readlines()
and print them as a list.
Q6. Write a Python program to strip newline characters when printing lines from a file.
Q7. Write a Python program to use with open()
to safely read a file, ensuring it is properly closed.
Q8. Write a Python program to count the number of lines in a file using a loop.
Q9. Write a Python program to read a binary file (e.g., an image) using 'rb'
mode and print its byte size.
Q10. Write a Python program to use read(0)
on a file and explain the result (it returns an empty string because 0 characters were requested).
Q1: What is the default mode of open()?
Q2: What does read() return?
Q3: What does readline() return?
Q4: Which method returns all lines as a list?
Q5: What is the use of with open()?
Q6: What happens if file does not exist in read mode?
Q7: What does "rb" mode do?
Q8: Which is more memory-efficient for large files?
Q9: What type is returned by f.read()?
Q10: After read() is called, where is the pointer?