# Writing files in background in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Here we are trying to do two tasks at a time, one in the foreground and the other in the background. We’ll write something in the file in the background and of a user input number, will find if it’s an odd or even number.

Doing multiple tasks in one program in python is possible through multithreading in

Live Demo

import threading
import time
def __init__(self, text, out):
self.text = text
self.out = out
def run(self):
f = open(self.out, "a")
f.write(self.text + '\n')
f.close()
time.sleep(3)
print ("Finished Background file write to " + self.out)
def Main():
message = input("Enter a string to store:" )
background = AsyncWrite(message,'out.txt')
background.start()
print ("The program can continue while it writes in another thread")
num = int(input("Entered number is : "))
if (num%2==0):
print("Entered number is Even")
else:
print("Entered number is ODD")
background.join()
print ("Waited until thread was complete")
if __name__ == '__main__':
Main()

## Output

Enter a string to store:Tutorialspoint
The program can continue while it writes in another thread
Entered number is : 33
Entered number is ODD
Finished Background file write to out.txt
Waited until thread was complete
Updated on 30-Jul-2019 22:30:24