0

How can I check when a file window is closed? I tried this:

import time
import os

path = input()
os.startfile(request)

try:
    file_path = open(path, 'rb')
except Exception:
    done = True
    while done:
        if file_path.closed:
            done = False
        time.sleep(SLEEP_TIME)

So the file starts before I start checking if the file is closed. Then, I open the file again, and because its open already, an exception should pop up, where I'm looping until the file is closed. I don't know whether the indication I made is right or not.

Please help!!! I'm desperate!!!

Tomer Bar
  • 11
  • 1

2 Answers2

0

You can't use file_path in the except: block, because the variable isn't assigned if open() raises an exception.

You should put the loop around the try/except, not inside the except.

while True:
    try:
        file_path = open(path, 'rb')
        break
    except:
        time.sleep(SLEEP_TIME)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

It will open the file only once, and if the file is already open it will use the already opened fie

import time

import os

path = 'bescom-17-apr.pdf'

try:
   with open(path, "r") as file:
       print("opened file")
except IOError:
   print("file not found")
Sadaf Shafi
  • 1,016
  • 11
  • 27