File Handling in Python
Tags: webdev, beginners, python, tutorial
Published: 2024-01-23 13:57:55

## Python File Handling

File handling is a crucial aspect of programming in Python, allowing you to read data from files, write data to files, and work with various file formats. 

In this article, we will explore:

- <a href="#read-write">Reading and Writing Files:</a>

Learn the skills required for reading from and writing to files in Python.

- <a href="#file-formats">Working with Different File Formats (e.g., JSON, CSV):</a>

Explore the versatility of file handling by working with popular file formats like JSON and CSV.

-  <a href="#error-handling">Handling Exceptions in File Operations:</a>

Learn how to implement error-handling strategies for robust file operations.

<h3 id = "read-write">Reading and Writing Files:</h3>

_Reading a file in Python:_


![Screen shot, showing how to read a file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fm5e8tbqrppl5iycy52f.png)

Here, we are opening a file named `file.txt` in the read mode `r`. The `read()` method is then used to read the entire content of the file and store it in a variable `file_contents`. We then use the `print` statement to print the contents and we close the file using the `close()` method


_Writing a file in Python_

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pepc1vab6nrsey37gs9.png)

In this example, the code opens a file named `file_write.txt` in write mode `w`. If the python doesn't exist python will create it. The `write()` method is then used to write the specified text to the file. Finally, we close the file using the `close()` method.

<h3 id = "file-formats">Working with Different File Formats (e.g., JSON, CSV):</h3>

_Writing data to `JSON` file:_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nlpe32seukf6sznozp2.png)

In this example, we first, create a Python dictionary named `data` to represent information. We then open a file named `data.json` in write mode `w`. The `with` statement is used, to ensure that the file is properly closed after writing or reading its content. The `json.dump()` function is used to serialize the Python dictionary into a JSON-formatted string and write it to the file. This is useful for storing structured data that can be easily shared and interpreted.

_Reading a file from a `JSON` file_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yfku0yk5302mdbsabwdp.png)

In this part, we open the 'data.json' file in read mode `('r')`. The `json.load()` function is then used to deserialize the JSON-formatted data from the file back into a Python dictionary. The loaded data is printed to the console.

_Writing on `CSV` file_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/somoqi9re36nwkdal5om.png)

In this example, we create a list of lists `(data_list)` to represent tabular data. We then open a file named `'data.csv'` in write mode `('w')`, and `csv.writer()` is used to create a CSV writer object. The `writerows()` method writes the entire list of lists to the CSV file, creating a table-like structure.

_Reading from `CSV` file_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iu78g9lcv7evwwjcu1qe.png)

Here, we open the 'data.csv' file in read mode `('r')` and use `csv.reader()` to create a CSV reader object. We then iterate through the rows of the CSV file, and each row is printed to the console. This allows us to work with tabular data stored in a CSV format.

<h3 id = "error-handling">Handling Exceptions in File Operations:</h3>


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rmi7tb2ybnom5akmr82.png)


- try Block:

The code within the `try block` attempts to open a file named 'nonexistent_file.txt' in read mode `('r')`.

Inside the `with` statement, `the file.read()` method is used to read the content of the file.

If the file doesn't exist, a `FileNotFoundError` exception is raised.

- except FileNotFoundError:

This block catches a specific type of exception - `FileNotFoundError`. If the file is not found, the code within this block is executed.
In this case, it prints a message instructing the user to check the file path.

- except Exception as e:

This block catches any other exception that might occur. It serves as a more general catch-all for unexpected errors.
The specific error message is printed to help diagnose the issue.

- else Block:

If no exceptions occur in the `try block`, the code within the `else block` is executed.

In this example, it prints `"File read successfully."`

- finally Block:

The `finally block` contains code that will always be executed, regardless of whether an exception occurred or not.

In this case, it prints "File handling process completed."
This is useful for cleanup operations or actions that must be performed regardless of the outcome.