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("[Link]", "w")
[Link]("Hello BOSS!\n")
[Link]("Welcome to Python file handling.")
[Link]()
Explanation:
- Opens '[Link]' in write mode.
- Writes two lines into the file.
- Closes the file after writing.
Reading from a File:
---------------------
Example:
file = open("[Link]", "r")
content = [Link]()
print("File Content:\n", content)
[Link]()
Output:
File Content:
Hello BOSS!
Welcome to Python file handling.
Appending to a File:
----------------------
Example:
file = open("[Link]", "a")
[Link]("\nThis line is newly added.")
[Link]()
Reading Line by Line:
----------------------
Example:
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
Using 'with' Statement:
------------------------
Example:
with open("[Link]", "r") as file:
print([Link]())
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.