如何在后台用Python编写文件?
null
这个想法是使用 多执行绪 在Python中。它允许我们在进行另一项操作时在后台写入文件。在本文中,我们将做一个“异步编写”。py’命名文件来演示它。这个程序在后台写一个文件的同时添加两个数字。 请在您自己的系统上运行此程序,以便查看生成的文件
Python3
# Python3 program to write file in # background # Importing the threading and time # modules import threading import time # Inheriting the base class 'Thread' class AsyncWrite(threading.Thread): def __init__( self , text, out): # calling superclass init threading.Thread.__init__( self ) self .text = text self .out = out def run( self ): f = open ( self .out, "a" ) f.write( self .text + '' ) f.close() # waiting for 2 seconds after writing # the file time.sleep( 2 ) 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 till the background thread is done background.join() print ( "Waited until thread was complete" ) if __name__ = = '__main__' : Main() |
输出:
Enter a string to store: HelloWorldThe program can continue while it writes in another thread100 + 400 = 500Finished background file write to out.txtWaited until thread was complete
程序将要求输入一个字符串,并计算两个数字的总和,然后在后台将“输入的字符串”写入名为“out”的输出文件。txt’。检查您的“异步写入”所在的目录。py文件存在,您还会找到一个名为out的文件。txt”,其中存储了字符串。
目的: 在后台编写文件的一般目的是,您可以在后台将数据添加到文件中,同时让程序在程序中执行另一项任务。例如,您可以在为同一用户执行另一项任务时,将从该用户收到的输入写入文件。
参考:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END