How to read data from text file in Python using File Handling?
To read data from a text file in Python, you can use several methods provided by Python's file handling features. Here are the most commonly used methods:
- read()
- readline()
- readlines()
Reading the Entire File with read()
The read() method reads the entire content of a file at once. This is useful when you want to read everything in the file as a single string.
Syntax:
file = open("filename.txt", "r")
content = file.read()
file.close()
Example:
file = open("example.txt", "r") # Open the file in read mode
content = file.read() # Read the entire file content
file.close() # Close the file
print(content)
Output:
This is the first line.
This is the second line.
Reading One Line at a Time with readline()
The readline() method reads a single line from the file each time it's called. This is useful for reading large files line-by-line to avoid loading the entire file into memory.
Syntax:
file = open("filename.txt", "r")
line = file.readline()
file.close()
Example:
file = open("example.txt", "r") # Open the file in read mode
line = file.readline() # Read the first line
print(line) # Print the first line
line = file.readline() # Read the second line
print(line) # Print the second line
file.close() # Close the file
Output:
This is the first line.
This is the second line.
Reading All Lines as a List with readlines()
The readlines() method reads all lines in the file and returns them as a list, where each line is an item in the list.
This is helpful when you want to access lines individually and apply list operations.
Syntax:
file = open("filename.txt", "r")
lines = file.readlines()
file.close()
Example:
file = open("example.txt", "r") # Open the file in read mode
lines = file.readlines() # Read all lines as a list
file.close() # Close the file
for line in lines:
print(line.strip()) # Print each line
Output:
This is the first line.
This is the second line.
Summary of Reading Methods
- read(): Reads the entire file as a single string.
- readline(): Reads one line at a time.
- readlines(): Reads all lines and returns a list, where each item is a line in the file.
Interview questions related to reading files in Python using file handling
Question 1. What is the purpose of using the read() method in Python file handling?
Answer: The read() method reads the entire content of a file at once and returns it as a single string. This method is useful when you need to process or display all of the file's content in one go.
Example:
file = open("example.txt", "r")
content = file.read()
file.close()
print(content)
Output:
This is the first line.
This is the second line.
Question 2. How does the readline() method differ from read() in Python file handling?
Answer: readline() reads only one line from the file at a time, which is helpful when working with large files to avoid loading the entire content into memory at once.
Example:
file = open("example.txt", "r")
print(file.readline()) # Reads the first line
print(file.readline()) # Reads the second line
file.close()
Output:
This is the first line.
This is the second line.
Question 3. What is the difference between readline() and readlines() methods?
Answer: readline() reads a single line from the file each time it is called, while readlines() reads all lines in the file and returns them as a list, where each line is an item in the list.
Example of readline():
file = open("example.txt", "r")
print(file.readline()) # First line
print(file.readline()) # Second line
file.close()
Example of readlines():
file = open("example.txt", "r")
lines = file.readlines() # Reads all lines as a list
file.close()
print(lines)
Output:
['This is the first line.\n', 'This is the second line.\n']
Question 4. Why is it important to close a file after reading it in Python?
Answer: Closing a file releases the resources associated with the file and ensures that any changes are saved. Failing to close a file can lead to memory leaks or file corruption.
Example:
file = open("example.txt", "r")
content = file.read()
file.close()
Question 5. What happens if you try to read a file that does not exist?
Answer: Python raises a FileNotFoundError if the specified file does not exist. Exception handling.
Example:
try:
file = open("nonexistent.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("File not found.")
Output:
File not found.
Question 6. How can you read the first 10 characters from a file?
Answer: You can pass an integer as an argument to read() to specify the number of characters to read.
Example:
file = open("example.txt", "r")
content = file.read(10) # Reads the first 10 characters
file.close()
print(content)
Output:
This is th
Question 7. Can you explain the difference between read() and readlines() in terms of output?
Answer: read() returns the entire content as a single string, while readlines() returns a list where each line is a separate item.
Example:
file = open("example.txt", "r")
print(file.read()) # Single string
file.close()
file = open("example.txt", "r")
print(file.readlines()) # List of strings
file.close()
Output:
Single string output:
This is the first line.
This is the second line.
List output:
['This is the first line.\n', 'This is the second line.\n']
Question 8. What is the purpose of the strip() method when printing lines read by readlines()?
Answer: The strip() method removes any trailing newline characters or whitespace from each line, providing a cleaner output.
Example:
file = open("example.txt", "r")
lines = file.readlines()
file.close()
for line in lines:
print(line.strip())
Output:
This is the first line.
This is the second line.
Question 9. Is it possible to use a for loop to iterate over lines in a file? How?
Answer: Yes, you can iterate over the file object directly with a for loop, which reads each line one by one.
Example:
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
Output:
This is the first line.
This is the second line.
Question 10. How can you check if a file is open or closed?
Answer: You can check the closed attribute of the file object. It returns True if the file is closed, and False if it is open.
Example:
file = open("example.txt", "r")
print(file.closed) # False, because file is open
file.close()
print(file.closed) # True, because file is closed
Output:
False
True
Tags:
Leave a comment
You must be logged in to post a comment.