Writing files in the background in Python



python3

# Python3 program to write a file to
# background

 
# Import streams and time
#modules

import threading

import time

 
# Inheriting the base class & # 39; Thread & # 39;

class AsyncWrite (threading.Thread): 

  

def __ init __ ( self , text, out):

 

# init superclass call

threading.Thread .__ init __ ( self

self . text = text

self . out = out

 

def run ( self ):

 

  f = open ( self . out, "a" )

f. write ( self . text + `` )

f.close ()

 

# wait 2 seconds after writing

# file

time.sleep ( 2 )

< code class = "undefined spaces">  print ( "Finished background file write to " ,

  self . out)

 

def Main ():

  

message = "Geeksforgeeks "

  background = AsyncWrite (message, `out.txt` )

background.start ()

 

print ( "The program can continue while it writes " )

  print ( " in another thread " )

print ( "100 + 400 =" , 100 + 400 )

 

# wait for the background thread to end

background.join () 

  print ( " Waited until thread was complete " )

 

if __ name__ = = `__main__` :

Main ()


Output:

 Enter a string to store: HelloWorld The program can continue while it writes in another thread 100 + 400 = 500 Finished background file write to out.txt Waited until thread was complete 

The program will ask you to enter string and calculates the sum of the two numbers, while in the background it writes the “entered string” to an output file named “out.txt”. Check the folder where the “Asyncwrite.py” file is located. exists and you will also find a file named & # 39; out.txt & # 39; which will store your string.

Purpose:
General purpose of the entry files in the background is that you can add your data to a file in the background, while at the same time forcing the program to perform another task in the program. You can write the received data from a user to a file when performing another task for the same user.

Link :

  • Python3 Basics
  • Python3 intermediate-level topics