2

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.

Andrew Morton
25.3k9 gold badges67 silver badges97 bronze badges
asked May 31, 2016 at 18:43
4
  • 1
    You should add some code so that we could help you. Commented May 31, 2016 at 18:52
  • 1
    Is 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. Commented 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 ! Commented May 31, 2016 at 18:58
  • You can use "try" and "except" for exception handling. Commented May 31, 2016 at 19:07

2 Answers 2

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.

answered Jun 1, 2016 at 20:18
Sign up to request clarification or add additional context in comments.

Comments

1

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--

answered May 31, 2016 at 19:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.