0

Target : If the file do not exist , stop run the next script

Code :

import glob ,os , sys
FL = []
for i in FL:
    if os.path.isfile(i):
        print("file exist")
    else:
        print("no such a file")
        sys.exit("check the errors before run the NEXT script")

print("This is the NEXT script")

Problem : Still return the result as

"This is the NEXT script"

Environment : Python 3.7 , Jupyter

Do i misunderstood the usage of sys.exit() ?

  • Since there are over 100 of lines to run if the files EXIST , thus i am avoiding put them all into the if TRUE statement loops. Welcome to point out if this mindset itself also a conceptual mistake programmatically.

1 Answer 1

1

Regarding:

FL = []
for i in FL:
    something

This will never execute something simply because the FL collection is empty. You are asking it do so something for each element in an empty list so obviously, it does it zero times.


What you need to do is to detect an empty list and handle that separately. You could do that by checking len(FL) beforehand, but Python has a nifty feature of the for loop that can be used to detect when the loop processed no items. This is the for..else feature.

Consider the code:

import sys
FL = []
for i in FL:
    print(i)
else:
    sys.exit("empty")
print("remainder")

This prints each item in the list but exits if there were none in it.


In terms of applying that to your code, it would be something like:

import glob ,os , sys
FL = []
for i in FL:
    if os.path.isfile(i):
        print(i, "file exists")
    else:
        print("no such file", i)
        sys.exit("check the errors before run the NEXT script")
else:
    print("no files in list")
    sys.exit("check the errors before run the NEXT script")

print("This is the NEXT script")
Sign up to request clarification or add additional context in comments.

1 Comment

thankyou your explanation help a lot . Actually it was collecting a list of file to run another processing . FL = glob.glob(os.path.join(path,"*.csv")) , If they are not exist , stop run : print("This is the NEXT script") , if they exist , run the next script : print("This is the NEXT script").

Your Answer

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.