Python File Handling
In this article, we will explore Python file handling with examples to more effectively meet the requirements of our learners.
Python file handling is a crucial component of every web application.
There are several Python functions for creating, reading, updating, and deleting files.
Python File Open
In Python file handling, open() is the primary function for working with files.
There are two parameters to the open() function; the filename and the mode.
A file can be opened in four unique ways (modes):
- “r” – Read – This is the default value. A file is opened for reading, and if it does not exist, an exception is thrown
- “a” – Append – Makes a file if one does not exist and prepares it for appending
- “w” – Write – Makes a new file if it does not exist, prepares a file for writing
- “x” – Create – Makes the given file, throws an exception if the file already exists
Furthermore, you can choose whether a binary or text file should be handled
- “t” – Text – Default value. Text mode
- “b” – Binary – Binary mode (e.g. images)
Python File Handling Syntax:
When dealing with Python files, mentioning the name of the file is all that is required to open it for reading:
ample_file = open("mrx.txt")
ample_file = open("mrexample/python/mrx.txt")
ample_file = open("mrx.txt", "rt")
ample_file = open("mrexample/python/mrx.txt", "rt")
The default values for read and text are “r” and “t”, respectively.
Reminder: You will receive an exception if the file does not found.
Python File Write
In this section we are examining Python file write with examples.
Create New File
By calling the open() method, you can make a new file in Python by providing one of the following parameters:
- “x” – Create – makes a file, throws an exception if the file already exists
- “a” – Append – makes a file if the given file is not found
- “W” – Write – makes a file if it does not found.
Make a file named “mrx_new.txt ”:
If the file is not present, create it:
Write an Existing File
When we talk about Python file write, you must pass a parameter to open() in order to write to an existing file:
- “a” – Append – adds a new line at the end of the file
- “w” – Write – overwrites any previously stored data
Append the following text to the file “mrx2.txt”:
Activate the “mrx2.txt” file. Replace the text in the file with:
Reminder: The entire file data will be replaced if you use the “w” method.
Python File Update
In Python file handling there is no built-in method or function to update data in files.
Thus, we have created a custom update methods for handling Python files.
The following example shows how to update the first appearance of a specific word in a file:
File Update First Instance Example:
This example shows how to update every instance of a specific word in a file:
File Update All Instance Example:
In the below example we have created two functions update_single_value() and update_multi_value() for updating the first instance and all instances of a specific word in a file.
Hence, we will be able to use them as needed in our Python programs:
File Update Custom Function Example:
Python Delete File
How to delete files in Python?
To eliminate a file with Python, you should import the OS module and call its os.remove() function:
Take out the file “mrx.txt”:
Delete File Example:1
Delete File Example:2
Check if File exist:
You may prefer to check if the file is present before eliminating it to avoid getting an exception:
Make sure the file is not present, then eliminate it:
Python Delete Folder
Utilize the os.rmdir() method to eliminate an existing folder:
Delete the folder “mrxfolder”:
Delete Folder Example:1
Eliminate the folder “amplefolder”:
Delete Folder Example:2
You now know what Python file handling is and how it works.
Python File Handling Uses
Here are some common uses of file handling in Python:
- Python file handling is often used to read data from files in various formats such as CSV, JSON, XML, or plain text. You can open a file, read its contents, and process the data for analysis, transformation, or further manipulation.
- File handling enables you to write data to files, creating new files or overwriting existing ones. You can store computed results, logs, configuration settings, or any other data that needs to be persisted outside the program’s runtime.
- Python file handling provides functionality for manipulating files, such as renaming, moving, or deleting files. You can programmatically organize, archive, or clean up files based on certain conditions or criteria.
- File handling is commonly used to read configuration files that store settings and parameters for a program. These files often use a specific format like INI or YAML. Python can read these files, extract the settings, and configure the program accordingly.
- Python’s logging module uses file handling to write log messages to files. You can configure logging to write different levels of log messages, timestamps, and other relevant information to log files for troubleshooting, debugging, or auditing purposes.