簡體   English   中英

如何檢測用戶何時關閉文件?

[英]How to detect when user closes a file?

我正在嘗試創建一個Python程序,用戶可以在其中將文本輸入到文件中。 關閉並保存文件后,我想打印其內容。 如何檢測用戶何時保存並關閉文件?

這是我用來打開文本文件的代碼。

def opentextbox():
    login = os.getlogin()
    file1 = open('C:/Users/'+login+'/enteryourmessagehere.txt', 'a')
    file1.close()
    subprocess.call(['notepad.exe', 'C:/Users/'+login+'/enteryourmessagehere.txt'])

opentextbox()

您可以在此處使用多線程。 創建一個線程,如下所示:

import threading
thread1 = threading.Thread(target=function[, args=arguments])

函數可以是這樣的:

import time
def function(file_handle):
  while 1:
    time.sleep(2) # Put your time in seconds accordingly
    if file_handle.closed:
      print "User closed the file"

並在主要功能繼續時在后台運行此線程。

或者您可以創建另一個線程,如果願意,並將其余代碼放在那里,同時運行兩個線程,您就完成了。

您可以使用subprocess.check_output()而不是subprocess.call() ,因為subprocess.check_output()等待程序退出。 要獲取文件的內容,可以使用file.read() 以下是您的代碼應如下所示:

def opentextbox():
    login = os.getlogin()
    subprocess.check_output(["notepad.exe", os.path.join("C:/Users", login, "enteryourmessagehere.txt")])
    file1 = open("enteryourmessagehere.txt", "r")
    contents = file1.read()
    print(contents)

我刪除了你的file1 = open(...)file1.close()行,因為它們沒有用處。 您沒有對該文件執行任何操作,因此您沒有理由打開它。 如果目的是確保文件存在,則可以使用os.path.isfile() 它不僅會檢查文件是否存在,還會查看它是否是文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM