delete a file works but with error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: delete a file works but with error (/thread-28310.html) |
delete a file works but with error - Leon79 - Jul-13-2020 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.") RE: delete a file works but with error - DPaul - Jul-13-2020 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 RE: delete a file works but with error - Leon79 - Jul-13-2020 (Jul-13-2020, 05:31 PM)DPaul Wrote: without seeing the details, you can delete a file only once. 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 Now it works thank you: try: os.remove(path) print("File deleted") except: print("ERROR WHILE DELETING THE FILE.") RE: delete a file works but with error - DPaul - Jul-14-2020 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 RE: delete a file works but with error - snippsat - Jul-14-2020 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.
|