Python Read Files


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 File

f = open("demo.txt", "r")
print(f.read())
f.close()

✅ Reads all content of the file as a single string.


🔹 read(n) – Read Specific Characters

f = open("demo.txt", "r")
print(f.read(10))  # Reads first 10 characters
f.close()

🔹 readline() – Read One Line

f = open("demo.txt", "r")
print(f.readline())
f.close()

✅ Use it again to read the next line.


🔹 readlines() – Read All Lines into List

f = open("demo.txt", "r")
lines = f.readlines()
print(lines)
f.close()

✅ Each line becomes an item in the list.


🔹 Loop Through Lines

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.


🔹 Use with Statement (Best Practice)

with open("demo.txt", "r") as f:
    content = f.read()
    print(content)

✅ Automatically closes the file after reading.


🔹 Read Binary File

with open("image.jpg", "rb") as file:
    data = file.read()

🔹 File Pointer Behavior

Each read() or readline() moves the pointer forward.


Practice Questions

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


Go Back Top