
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Writing Files in the Background in Python
In this tutorial, we will learn about the multi-threading in Python. It helps us to perform multiple tasks at a time. Python has a module called threading for multitasking.
We see how it works by writing data to a file in the background while calculating the sum of elements in a list. Let's see the steps involved in the program.
Import the threading module.
Create a class by inheriting threading.Thread class.
Write the file code inside the run method in the above class.
Initialize the required data.
Write the code to calculate the sum of numbers in a list.
Example
# importing the modules import threading # creating a class by inhering the threading.Thread base class class MultiTask(threading.Thread): def __init__(self, message, filename): # invoking the Base class threading.Thread.__init__(self) # initializing the variables to class self.message = message self.filename = filename # run method that invokes in background def run(self): # opening the file in write mode with open(filename, 'w+') as file: file.write(message) print("Finished writing to a file in background") # initial code if __name__ == '__main__': # initializing the variables message = "We're from Tutorialspoint" filename = "tutorialspoint.txt" # instantiation of the above class for background writing file_write = MultiTask(message, filename) # starting the task in background file_write.start() # another task print("It will run parallelly to the above task") nums = [1, 2, 3, 4, 5] print(f"Sum of numbers 1-5: {sum(nums)}") # completing the background task file_write.join()
It will run parallelly to the above task
Sum of numbers 1-5: 15
Finished writing to a file in background
Output
You can check the directory for the file. If you run the above code, you will get the following output.
It will run parallelly to the above task Sum of numbers 1-5: 15 Finished writing to a file in background
Conclusion
If you have any queries from the tutorial, mention them in the comment section.