4

I am trying to create a Python program where the user can input text into a file. After they close and save the file, I want to print its content. How do I detect when the user has saved and closed the file?

This is the code I have used to open the 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()
1

2 Answers 2

1

You can use multi-threading here. Create a thread, something like this:

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

Where function can 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 goes on.

Or you can just create another thread, if you will, and put the rest of your code there, run the two threads simultaneously and you're done.

0

You can use subprocess.check_output() instead of subprocess.call(), because subprocess.check_output() waits for the program to exit. To get the contents of the file, you can use file.read(). Here is what your code should look like:

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)

I removed your file1 = open(...) and file1.close() lines, because they serve no purpose. You aren't doing anything with the file, so you have no reason to open it. If the purpose was to make sure the file exists, you can use os.path.isfile(). It will check not only to see if the file exists, but also to see if it is a file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.