0

On a Windows OS, I use a python script that open an image in paint, using:

os.system("start %s" % path)

User suppose to edit the image, save the changes and close the file.

I wish the program will wait in a loop till the file is close, and then continue to run.

I tried:

time.sleep(5)
while True:
    try:
        myfile = open(path, "r+")
    except IOError:
        continue
    break
myfile.close()

It seems to break the loop also if I don't close the file. time.sleep(5) is to make sure the file got open successfully, and we don't have some timing issues.

Instead of myfile = open(path, "r+") I tried to use os.rename(), as someone advised here, but it does the opposite - stay in the loop even after I close the file.

It seems duplicate from here, but the solution there fits only for Excel files and I couldn't find an answer that fulfill my wish.

Thanks!

2
  • Could you explain in detail what you are trying to achieve? Not sure to get what your problem really is and what you need.
    – deponovo
    Commented Oct 6, 2020 at 11:07
  • I want my program to go through many images, run some code that check if an image is "valid" or not. In case it is not valid, I want it to open in "paint" program, user manually fix it, and close it. After he is done, the program will carry on, so it can open for the user a new invalid image to fix. I don't want to open them all, but to wait until the user finished to fix an image, before I open a new one to fix.
    – Shaq
    Commented Oct 6, 2020 at 11:18

1 Answer 1

1

Maybe you would prefer to use the context manager version:

with open(file_path, 'r') as f:
    # do something with f
# f is closed now

This is closing the file automatically for you.

Edit: It seems the OP wants to launch Windows paint with an image that has been (somehow) detected to need some user editing. An alternative to achieve this would be: while looping through the images make a simple call to:

path_to_image = <image_file_path_here>
os.system(f'mspaint {path_to_image }')

this will open Paint with the desired image and the program will only continue execution once the Paint window is closed.

2
  • But it opens it in python.. not in a new window in "paint" program for to user to edit, am I correct?
    – Shaq
    Commented Oct 6, 2020 at 11:15
  • After edit - simple, clean, and great solution that works just great :)
    – Shaq
    Commented Oct 6, 2020 at 12:08

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