# Writing files in the background in Python

PythonServer Side ProgrammingProgramming

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.

• 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
def __init__(self, message, filename):
# invoking the Base class
# 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
# starting the task in background
file_write.start()
print("It will run parallelly to the above task")
nums = [1, 2, 3, 4, 5]
print(f"Sum of numbers 1-5: {sum(nums)}")
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.

Published on 12-Feb-2020 13:00:59