Practical 5: Python program to read and display the contents of a file.
Problem Statement
Write a Python program to read and display the contents of a file.
Solution Code
# Program to read and display file contents
# Open the file in read mode
file = open("output.txt", "r")
# Read the entire file content
content = file.read()
# Display the content
print("File Contents:\n")
print(content)
# Close the file
file.close()
Output
If the file output.txt contains the following data:
Hello, this is line 1.
This is line 2.
Writing to a file using writelines(). This is an appended line.
Appending another line to the file.
After running the program, the output will be:
File Contents:
Hello, this is line 1.
This is line 2.
Writing to a file using writelines().
This is an appended line.
Appending another line to the file.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 5 solution where we have written Python program to read and display the contents of a file.
- Opening the File in Read Mode
- open(“output.txt”, “r”) opens the file in read mode (r), allowing us to read its content.
- Reading File Content
- file.read() reads the entire file content and stores it in a variable.
- Displaying the Content
- The stored content is printed to the console.
- Closing the File
- file.close() ensures proper resource management by closing the file after reading.
Key Concepts Learned
- File Handling in Python
- Using open() with read mode (r) to access a file.
- Reading File Content
- read() method reads and returns the entire file content as a string.
- File Closing for Resource Management
- Ensuring the file is closed after use to prevent memory leaks.