Is mastering the file writing function crucial for software applications that consistently manage and store data? However, it is used because of the ability to write data in files and allows programs to store and save data for future use. It is like a digital notebook where you can jot down all the necessary information. Writing to files is crucial for applications where you need to store user preferences, save game progress, and reserve the data permanently. So, all these can be attained by one of the file handling operations i.e. write(). In this article, you will explore the various aspects of file handling in Python, its writing and appending operations, and the multiple modes of writing to file required for performing different tasks with coding examples.
Importance of Writing Data to Files
In Python, writing to files plays a very significant role in developing an application where data is stored persistently. So, before moving towards the detailed knowledge of file writing, let's take a few moments to see why we need file-handling writing operations in software development.
- Use for writing the configuration files of the application. Developers use file handling to write the settings and parameters of applications in configuration files so that they don't need to change the code for different environments.
- Use for managing the persistence of application data. Primarily, the data is stored in a hard drive when the application is closed, but it allows the application to retrieve the saved progress of the application when it runs.
- Use for backup and recovery of application data in case of data loss during the application sessions. Writing files will create the backup of the critical data and ensure the data integrity upon application failure.
Overview of File Writing Operations in Python
Python provides us with many built-in file-handling writing operations by which you can write and store data in the file. There are two primary operations for writing data to file, i.e. write and append. The write() operation of file handling is used for writing, updating, and storing data in files. The append operation is also performed by the write() operation and used for the same purpose but with a different use case. So, these file-handling operations will not only ensure the file-writing works smoothly, but also help to manipulate the complex files as well.
Flow Diagram: File Handling Writing Process
Introduction to File Modes for Writing to Files
To write data in a file, we need to open the file in a mode that provides us with the facility of writing data. These modes specify the position of the pointer whether at the beginning or the end of the file.Three modes are defined to write data into the file. These are:
- "w" mode: It is used for performing writing operations in the file. It opens the file and overwrites the data. If the file does not exist, then it will create the file, or else it will remove the content and start writing from the beginning of the file.
- "a" mode: It is used for appending the data in the file. If the file does not exist, then it will create the file or else append the content at the end of the file.
- "x" mode: It is used for creating the file and opening the file in writing mode. When a file does not exist, then this mode is used to create the file. If the file exists with the same name, it will throw the error “FileExistError”. It also ensures not to overwrite the existing file.
Opening Files for Writing
1. Using "open()" Function
When working with writing operations, the first step is the open() function. This function opens the file while providing various file-handling operations including reading, writing, appending, and accessing the file. It requires at least one argument for accessing the file, i.e. the file path. The syntax is:
File = open('Content.txt') #this line will open the file locate at this path
2. Specifying File Paths and Modes for Writing
For opening the file, the file path is mandatory to provide, as it will help the compiler locate the file. So, it is important to provide the path of the desired file you want to access, i.e. relative or absolute path. The second argument is to specify the mode of the file. Here, I am performing writing operations, so the mode is 'w'.
file_path = 'Context.txt' #file path at current directory
file = open(file_path, 'w') #this line will open the file located at this path within the reading mode
3. Handling File Objects and File Descriptors for Writing
After opening the file, Python will create the object of the file needed for further accessing the operations like write(), close(), and so on. At the operating system level, the file descriptor will assign the reference no that are non-negative integers to the opened file that is internally handled by Python itself. These file descriptors will allow you to interact with the file and keep track of file content.
file_path = "Content.txt" #provide location of file in the same directory
file = open(file_path, 'w') #here, the file open operation is performed with write mode
file.write("Python is the versatile programming language.") #write function will add the line in the file
file.close() #after using the file, it will close the file
file = open(file_path, 'r') #here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
file.close() #after using the file, it will close the file
In while open(file_path, mode) as file, the file is the handler that is used for using file handling operations.
Output
Writing Data to Files
After successfully opening the file, you can perform various operations. Here, I am going to discuss the writing to files operation, i.e. write(). Let's delve into the details of how you can use this function in distinct ways.
1. Writing Strings to Files: Using the "write()" Operation
After defining the file mode as ‘w’, we can use the multiple writing operations. All the data in the file is by default written as a string. Using the write() operation, we can write string data in the file. Sometimes, you need to write data other than strings, then we can convert the data into strings first.
file_path = "Content.txt" #provide location of file in the same directory
#used for performing writing operation
with open(file_path, 'w') as file: #here, the file open operation is performed with write mode
file.write("Python was created by Guido van Rossum") #write function will add the line in the file
#this is used for reading operation
with open(file_path, 'r') as file:#here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
When you started writing into the file be attentive this would remove the existing content of the file.
Output
2. Writing Multiple Lines: Using newline character
If you want to write multiple data in the file, you can use the write() operation for each line. Breaking down the whole data into distinct lines will make the clear and organized structure of the file. It should be maintained to make it readable and understandable. But for that, you must use “\n” new line to separate each line.
file_path = "Content.txt" #provide location of file in the same directory
#used for performing writing operation
with open(file_path, 'w') as file: #here, the file open operation is performed with write mode
file.write("Python is a versatile programming Language\n") #\n will move the cursor to the new line
file.write("Python was created by Guido van Rossum\n") #write function will add the line in the file
file.write("It is first released on February 20, 1991")
#this is used for reading operation
with open(file_path, 'r') as file:#here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
Remember, \n is used to add ewline into the file.
Output
3. Writing Data from Iterable Objects: Having Non-String Data
As we know, when we write data in the file, it is stored as a string by default. But for writing non-string data, we first have to convert the data into string form using the str() function. Also, if we have a list of data that we want to add to the file, we can do this by using the iterable object. Let's see the code example.
file_path = "Content.txt" #provide location of file in the same directory
#used for performing writing operation
with open(file_path, 'w') as file: #here, the file open operation is performed with write mode
names = ['Mohammad Ahmad', 'Lina Omar', 'Moath Ahmad']
Score = [95, 99, 90]
file.write("STUDENT RECORD\n") #\n will move the cursor to the new line
for student_Name in names: #iterable object for names
file.write(student_Name + "\n")
for marks in Score: #iterable object for marks
file.write(str(marks) + "\n") #covert non-string into string
#this is used for reading operation
with open(file_path, 'r') as file:#here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
Output
Writing Data to Binary Files: Overview of Binary Files
It is the normal routine in Python when you need to save the data in binary form. Binary files contain data that is not human-readable and only processed by the computer. Mostly, it is used when the data is in non-textual form like images, videos, etc. Also, the computer only understands and works with binary data therefore, in some situations, there is a need to use binary form instead of simple textual data. Python provides us with a very convenient way of dealing with binary files by just specifying the mode as “wb”.
Writing Binary Data to Files
For writing the binary data to the file, we need to open the file in binary mode. Here, the data is provided in the form of bytes strings, or buffers.
file_path = "binary_file.bin" #provide location of file in the same directory
#used for performing writing operation
with open(file_path, 'wb') as file: #here, the file open operation is performed with write binary mode
binary_data = b"\x48\x65\x6C\x6C\x6F\x2C\x20\x57\x6F\x72\x6C\x64\x21"
file.write(binary_data) #print the binary data in the file
#this is used for reading operation
with open(file_path, 'r') as file:#here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
For performing both reading and writing together you can use the w+ mode.
Output
Exception Handling with File Writing Operation
It's important to handle exceptions beforehand while coding the application, such as using try-except blocks when working with file operations to handle potential exceptions gracefully related to FileNotFound or FileExist errors. Here, in the example, I use the try-except-finally block while performing the open() operation with write() using ‘x’ mode so it would handle the error if the file does not exist or is not located at a given location. Also, if the file is already available it will throw the exception.
import json
file_path = "sample4.json" #provide location of file in the same directory
#used for performing append operation
try:
with open(file_path, 'x') as file: #here, the file open operation is performed with write mode
data = {
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
json.dump(data, file) #it dups the serial data into the file using json dump function
except FileNotFoundError as e: #if file not found
print("Provide correct File Path")
except FileExistsError as e: #if file is already exist
print("File already exist")
else:
print("No exception found")
finally:
print("Writing operation performed successfully")
#this is used for reading operation
with open(file_path, 'r') as file: #here, the file open operation is performed with read mode
print(file.read()) #print what we write in the file
Output
Q: Can I use multiple files for writing operations at the same time?
A: Yes, you can write on multiple files at a time by providing the list of file paths with open() and using the for loop for iterating at each file.
Q: What is the writeline() function?
A: The writeline() function is one of the writing operations that is used for writing the list of strings in the file.
Q: Does write() and writeline() have the same functionality?
A: No, the write() operation will write a string in the file whereas the writeline() will write the list of strings in the file.
Wrapping up
In conclusion, we got to know in detail that data persistence and manipulation required a detailed knowledge of file handling and its writing operation. Throughout this article, we talked about the different modes of file handling with our major focus on writing operations that we performed on different files i.e. textual files and binary files. Also, we understand the use of exception handling in code that helps us to prevent the code from behaving unexpectedly. The developer needs to update according to the technology as it advances and is always cautious with sensitive data. I hope this guide is helpful for you. Happy Coding!
Reference
Write to File