File Handling in Python - Reading and Writing (10 Marks)
In Python, file handling is used to perform operations such as creating, reading, writing, and
appending files. Python provides built-in functions for file handling using the open() function.
File Modes:
- 'r' - Read (default)
- 'w' - Write (creates or overwrites a file)
- 'a' - Append (adds to the end of the file)
- 'x' - Create a new file
Writing to a File:
-------------------
Example:
file = open("example.txt", "w")
file.write("Hello BOSS!\n")
file.write("Welcome to Python file handling.")
file.close()
Explanation:
- Opens 'example.txt' in write mode.
- Writes two lines into the file.
- Closes the file after writing.
Reading from a File:
---------------------
Example:
file = open("example.txt", "r")
content = file.read()
print("File Content:\n", content)
file.close()
Output:
File Content:
Hello BOSS!
Welcome to Python file handling.
Appending to a File:
----------------------
Example:
file = open("example.txt", "a")
file.write("\nThis line is newly added.")
file.close()
Reading Line by Line:
----------------------
Example:
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
Using 'with' Statement:
------------------------
Example:
with open("example.txt", "r") as file:
print(file.read())
Advantage:
- Automatically closes the file after reading or writing.
Conclusion:
File handling in Python is essential for storing and processing data. The read and write operations
help manage external files efficiently.