File Handling in Python
File Handling in Python
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.
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()
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.