4

Within my script I have one large While: try: loop. Within this, I have want to increase some pointers in the case that a picture was successfully downloaded from my camera and resized, here is what my code looks like within my larger python script:

import os.path
try os.path.isfile('/home/pi/CompPictures' + picturenumber + '.JPG'):
    os.system('sudo rm /home/pi/Pictures/IMG_0001.JPG')
    os.system('sudo rm /home/pi/output.bin')
    picturenumber = int(picturenumber))+1
except:
    pass

picturenumber contains a string '1' to start and then will increase.

I'm only wanting this to run one. So essentially I'm running through my larger code continuously, then for every sweep through the larger loop, I want to check this try statement once and if the file exists, delete some files and increase the pointer.

I'm getting the following error.

  File "pijob.py", line 210
    try os.path.isfile('/home/pi/CompPictures' + picturenumber + '.JPG'):
         ^
SyntaxError: invalid syntax

Extremely new to python...so hope it isn't a simple mistake :(

4 Answers 4

8

You need a new line and a :. Try this:

try:
    os.path.isfile('/home/pi/CompPictures' + picturenumber + '.JPG') #
    os.system('sudo rm /home/pi/Pictures/IMG_0001.JPG')
    os.system('sudo rm /home/pi/output.bin')
    picturenumber = int(picturenumber))+1
except:
    pass

You can include a finally statement to execute code regardless of the outcome:

try:
    #code
except:
    pass
finally:
    #this code will execute whether an exception was thrown or not
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I'm wanting code that checks to see if a file exists and then if it does, delete some files and increase a pointer. It seems the try statement may not be the best since no matter what, it deletes the files and increases the pointer regardless of if the file exists. Maybe I should be trying another statement?
You can check if the file exists with: if filename in os.listdir('path/to/dir'):. Does that help?
Seems like it would. Is the syntax simply if filename in os.listdir('path/to/dir'): stuff with no "exit" type syntax? thank you!
You will need a new line and an indent after the if filename in os.listdir('path/to/dir'):. Then you write code that you would want to execute if the file exists. Also, if this answered your question, you should accept it as correct to help other people that visit this page in the future. =)
didn't even know "accept as correct" was an option x_x. learning.
6

try like this,

import os.path
try :
    os.path.isfile('/home/pi/CompPictures' + picturenumber + '.JPG') #
    os.system('sudo rm /home/pi/Pictures/IMG_0001.JPG')
    os.system('sudo rm /home/pi/output.bin')
    picturenumber = int(picturenumber))+1
except:
    pass

python try syntax,

try:
   some_code
except:
   pass

3 Comments

Quick question, if it goes through the try and hits that first os.path.isfile and cannot open the file...what happens? does it exit the try?
@user2208604 If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. docs.python.org/3/tutorial/errors.html#handling-exceptions
Maybe I should be trying something other than the try statement, because I'm only wanting the two os.system commands and the one picturenumber increase to run if that file exists. If the file does not exist, I'm wanting the jump out of this and continue with my larger script loop. Could you, perhaps, point me in the right direction for something for this? Thanks.
1

The syntax for try/except in Python is

try:
    # code that might raise the exception
    pass
except <exceptions go here>:
    # code that should happen when the
    # specified exception is/exceptions are
    # raised
    pass
except <other exceptions go here>:
    # different code that should happen when
    # the specified exception is/exceptions
    # are raised
    pass
else:
    # code that follows the code that 
    # might raise the exception, but should
    # only execute when the exception isn't
    # raised
    pass
finally:
    # code that will happen whether or not
    # an exception was raised
    pass

A couple of general guidelines:

  • Unless you really want your code to silently handle all exceptions, catch specific exceptions. This will allow you to better handle anything that goes wrong.
  • When using multiple except blocks, place blocks with more specific exceptions higher up (i.e., make sure subclassed exceptions appear before their base). The first block with a matching exception will win.
  • Place as little code as possible under the try. Any code that can raise an exception you are expecting belongs in the try; any code that should execute only when no exception is raised should go inside the else. That way if it raises an exception you weren't expecting it doesn't get squashed.

Also, you may want to take a look at the subprocess module instead of using os.system().

Comments

0

if you want to see if the file exist just try this:

check_file = os.path.isfile("data/login_data/data.prx")
if check_file == False:
    print("cannot find the file")
if check_file == True:
    print("the file already exists")

Comments

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.