Python Forum

Full Version: delete a file works but with error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I get an error from my code, I create the path in order to delete the correct file (I have import os of course), even if my code delete the correct file, in the terminal I get the following error:

ERROR WHILE DELETING THE FILE.

It doesn't write file deleted, but it deletes the file.

Why I get this error if the code delete the file anyway?


myfile = "test.png"
currentdir = os.getcwd()
path = currentdir + "/static/images/" + myfile

if os.path.exists(path):
    print("File deleted")
    os.remove(path)
else:
    print("ERROR WHILE DELETING THE FILE.")
without seeing the details, you can delete a file only once.
Assuming that is it there the first run, I do not see you rewriting it, so
it can be deleted again.
Instead of if .. else, you may also do a try...except...

my 2 cts,
Paul
(Jul-13-2020, 05:31 PM)DPaul Wrote: [ -> ]without seeing the details, you can delete a file only once.
Assuming that is it there the first run, I do not see you rewriting it, so
it can be deleted again.
Instead of if .. else, you may also do a try...except...

my 2 cts,
Paul



Yes of course it's the first attempt, when the code deletes it I add it back to try again.

Now I followed your suggestion, I just changed it like this:


myfile = "test.png"
currentdir = os.getcwd()
path = currentdir + "/static/images/" + myfile

try:
    os.remove(path)
    print("File deleted")
except:
    print("ERROR WHILE DELETING THE FILE.")
And I get both the messages:

File deleted
ERROR WHILE DELETING THE FILE.

Why this? It simply needs to delete a file... I can't understand Confused

Now it works thank you:


try:
os.remove(path)
print("File deleted")
except:
print("ERROR WHILE DELETING THE FILE.")
Hi,

In the except: clause, you print your own message,
but tthe idea is that you let python determine what the problem is.
Maybe it is something else !
So you might do this:
except Exception as e:
    print (e.args)
Paul
The first code should work.
Try in a other environment,here a repl.it link.
Using os.path.join() or PurePath pathlib can be better when joining paths.