I am a relative newbie to Python, and I have searched and while there are many posts regarding the error, none appear to address my requirement.
Briefly, I am writing code to hourly reports. I intend to have 4 days of reports archived in the folder. At the beginning of my code I have one line that deletes all 24 files for reports generated 5 days earlier.
The first run is fine, as the program finds files to delete, so it will continue to run to a successful completion. However, the next 23 runs will fail as the programs fails with a "No such file or directory" error.
My work-around is to write code where it only executes the "delete" function on the first hour's run, but I consider that just a band-aid solution. I would prefer to code an exception so that the remaining code is processed even though the first step got that error.
-
1You should add some code so that we could help you.Gynteniuxas– Gynteniuxas2016年05月31日 18:52:22 +00:00Commented May 31, 2016 at 18:52
-
1Is How to check whether a file exists using Python? of use to you? So you can check if the file exists before attempting to delete it.Andrew Morton– Andrew Morton2016年05月31日 18:54:22 +00:00Commented May 31, 2016 at 18:54
-
Why not tweak your work around to only execute the "delete" function if the files exist rather than on the first hours run !Alan Kavanagh– Alan Kavanagh2016年05月31日 18:58:51 +00:00Commented May 31, 2016 at 18:58
-
You can use "try" and "except" for exception handling.Vivek– Vivek2016年05月31日 19:07:59 +00:00Commented May 31, 2016 at 19:07
2 Answers 2
If the file it wants to delete is not in the directory, I want that to be okay and the program to continue processing the next command instead of aborting the process. In short I want to check to see if the file is there and if it isn't skip the rm code and process the rest of the script.
Comments
Figures that I would wrestle with this for a couple of days and then figure it out 30 min after I post the question. Here's the solution:
if not listdir("insert the work path here"): --the command I want to execute if the dir is not empty-- Else: --whatever code you want to execute when dir is empty--
--Code you want to execute every time the program is run, whether the directory is empty or not--