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:
Learn the skills required for reading from and writing to files in Python.
Explore the versatility of file handling by working with popular file formats like JSON and CSV.
Learn how to implement error-handling strategies for robust file operations.
Reading and Writing Files:
Reading a file in Python:
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
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.
Working with Different File Formats (e.g., JSON, CSV):
Writing data to JSON
file:
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
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
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
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.
Handling Exceptions in File Operations:
- 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.
Top comments (0)