'Prevent error console from appearing using .exe file

I have created an exe file using autopy to exe.

At the beginning, I ask the user to enter the file to use using the following code:

filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")

But when the user click on "Cancel" or hit the "X" in the upper right side, an error code appear as you can see on the image

Error Code

how to stop the code from continue running if the user click one of the two option mentioned above so that the error code will not appear?

I know some questions have already been asked about similar subject but I couldn't adapt them to my case. I hope I have been clear enough



Solution 1:[1]

The root cause of the FileNotFoundError is that it cannot find the file with an empty string path, which it will never find that one.

I will elaborate on what @Sagitario has explained. The os.path.exists(filename) used to check if the filename is valid and exists or not:

import os

if os.path.exists(filename):
    do_something() # like trying to open a file in this condition.
else:
    print(f"{filename} not found, please select other path")

Nevertheless, if your path is empty, it will surely go in an else condition. Instead, you can check the path input that it's not empty and exists.

In addition, the try-except block can help handle the error here. But you also need to solve the main problem of an empty file path somewhere in your code, by using the above if condition to verify the file path.

try:
    filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
    # ...  the rest of your code relating the file opening ...
except FileNotFoundError:
    print(f"{filename} not found, please select other path")

Solution 2:[2]

Just check if the provided path exists with os.path.exists(filename)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fony Lew
Solution 2 Sagitario