在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