How to determine when a user closes a file?

I am trying to create a Python program where a user can enter text into a file. After closing and saving the file, I want to print its contents. How to determine when a user has saved and closed a file?

This is the code I used to open a text file.

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()
+4
source share
2 answers

Here you can use multithreading. Create a stream, something like this:

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

If the function might be something like this:

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"

And run this thread in the background while your main function continues.

Or you can just create another thread if you want, and put the rest of your code there, run both threads at the same time, and you're done.

+1

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(). , , , .

0

Source: https://habr.com/ru/post/1628098/


All Articles