File Handling

File handling in Python allows you to work with files, including opening, reading, and writing data. Here's an explanation of opening, reading, and writing files, file modes and file objects, as well as error handling with try-except blocks:

Opening, Reading and Writing Files

In this example, the open() function is used to open a file named data.txt in read mode ("r"). The content of the file is then read using the read() method of the file object and stored in the content variable. Finally, the file is closed using the close() method.


For writing, a file named output.txt is opened in write mode ("w"). The text "This is some text." is written to the file using the write() method, and then the file is closed.

File modes and file objects

Error handling with try-except blocks

In this example, the try-except block is used to handle potential exceptions that may occur when opening and reading the file. If a FileNotFoundError or PermissionError is raised, the corresponding block of code within the except block is executed, printing an appropriate error message.

Error handling allows you to handle unexpected situations when working with files and ensures that your program doesn't crash due to file-related issues.

File handling is a crucial aspect of working with external data and is essential for tasks such as reading input files, processing data, and writing output files. It provides a way to interact with files stored on the system, enabling data storage, retrieval, and manipulation within your Python programs.