在Python中后台写入文件
在本教程中,我们将学习Python中的多线程。它帮助我们一次执行多项任务。Python有一个名为threading的模块,用于多任务处理。
让我们看看它如何工作:在后台将数据写入文件,同时计算列表中元素之和。我们来看看程序中涉及的步骤。
导入threading模块。
创建一个类,继承threading.Thread类。
在上述类的run方法中编写文件代码。
初始化所需数据。
编写计算列表中数字之和的代码。
示例
# 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()它将与上述任务并行运行
1-5 数字之和:15
完成在后台写入文件
输出
您可以在目录中查看文件。如果您运行上述代码,将获得以下输出。
It will run parallelly to the above task Sum of numbers 1-5: 15 Finished writing to a file in background
结论
如果您对本教程有任何疑问,请在评论部分中提及。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP