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 ”:

Example: 

ample_file = open("mrx_new_myfile.txt", "x") if open("mrx_new.txt"): print("The file is created successfully") else: print("File is not created successfully")

Example: 

ample_file = open("mrx_new.txt", "a")if open("mrx_new.txt"): print("The file is created successfully") else: print("File is not created successfully")

If the file is not present, create it:

Example: 

ample_file = open("mrx_new.txt", "w")if open("mrx_new.txt"): print("The file is created successfully") else: print("File is not created successfully")

Python File Handling example

Example: 

ample_file = open("mrx_new.txt", "w") ample_file.write("Here is the new mrx text file") ample_file.close()ample_file = open("mrx_new.txt", "r") print(ample_file.readline())

 


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”:

Example: 

ample_file = open("mrx2.txt", "a") ample_file.write("Here is the second txt file of mrx") ample_file.close() #After the appending, open the file and read it: ample_file = open("mrx2.txt", "r") print(ample_file.read())

Example: 

ample_file = open("mrx2.txt", "a") ample_file.write("\nIt's the second line of mrx2.txt") ample_file.write("\nIt's the third line of mrx2.txt") ample_file.close()ample_file = open("mrx2.txt", "r") print(ample_file.read())

Activate the “mrx2.txt” file. Replace the text in the file with:

Example: 

ample_file = open("mrx2.txt", "w") ample_file.write("Oh no, I accidentally deleted the content!") ample_file.close() #The file should now be open and read as follows: ample_file = open("mrx2.txt", "r") print(ample_file.read())

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: 

print("FILE DATA WITHOUT UPDATE")ample_file = open("mrx1.txt", "r") ample_file = ample_file.read() print(ample_file)print("UPDATED FILE DATA")import research = "file" rep = "document"match = re.search(r"\b"+search+r"\b", ample_file)if match: print("Exact string found.")new_text = ample_file.replace(match.group(), rep, 1) with open('mrx1.txt', 'w') as f: f.write(new_text) with open('mrx1.txt', 'r') as f: text = f.read() print(text) else: print("Exact string not found.")

This example shows how to update every instance of a specific word in a file:

File Update All Instance Example: 

ample_file = open("mrx.txt", "r") ample_file = ample_file.read() print(ample_file)import research = "file" rep = "document"match = re.search(r"\b"+search+r"\b", ample_file)if match: print("Exact string found.")new_text = ample_file.replace(match.group(), rep) with open('mrx.txt', 'w') as f: f.write(new_text) with open('mrx.txt', 'r') as f: text = f.read() print(text) else: print("Exact string not found.")

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: 

import redef update_single_value(file_name, search, replace): with open(f'{file_name}', 'r') as f: text = f.read() match = re.search(r"\b"+search+r"\b", text)if match: print("Exact string found.")new_text = text.replace(match.group(), replace, 1) with open(f'{file_name}', 'w') as f: f.write(new_text) with open(f'{file_name}', 'r') as f: text = f.read() print(text) else: print("Exact string not found.")def update_multi_value(file_name, search, replace): with open(f'{file_name}', 'r') as f: text = f.read() match = re.search(r"\b"+search+r"\b", text)if match: print("Exact string found.")new_text = text.replace(match.group(), replace) with open(f'{file_name}', 'w') as f: f.write(new_text) with open(f'{file_name}', 'r') as f: text = f.read() print(text) else: print("Exact string not found.")update_multi_value("mrx.txt", "file", "document") update_single_value("mrx1.txt", "file", "document")

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 

import os os.remove("mrx.txt")Delete the file "mrx2.txt":

Delete File Example:2 

import os os.remove("mrx2.txt")

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:

Example: 

import os if os.path.exists("mrx.txt"): os.remove("mrx.txt") else: print("File is not found")

Example: 

import os if os.path.exists("mrx_new.txt"): os.remove("mrx_new.txt") else: print("File is not found")

Python Delete Folder

Utilize the os.rmdir() method to eliminate an existing folder:

Delete the folder “mrxfolder”:

Delete Folder Example:1 

import os os.rmdir("mrxfolder")

Eliminate the folder “amplefolder”:

Delete Folder Example:2 

import os os.rmdir("amplefolder")
Reminder: Unfilled folders can only be deleted.

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
Subscribe to our Newsletter and stay informed about the latest technical developments.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *