1
\$\begingroup\$

I am learning programming with Python. I am not sure if I can write a try/except block like this.

import os
import shutil
try:
    shutil.rmtree('c:/guna/newCAT1')
    print("dir newCAT1 deleted")

except:
    os.mkdir('c:/guna/newCAT1')
    print("dir newCAT1 created")
    fileIN=open('c:/guna/newCAT1/secretMSG.txt','w' )
    fileIN.writelines("the dog is green")
    fileIN.close()
else:
    print("exception code did not execute")
    os.mkdir('c:/guna/newCAT1')
    print("dir newCAT1 created")
    fileIN = open('c:/guna/newCAT1/secretMSG.txt', 'w')
    fileIN.writelines("the dog is green")
    fileIN.close()
\$\endgroup\$
2
  • 2
    \$\begingroup\$ What do you mean you’re not sure? \$\endgroup\$
    – AMC
    Commented Jan 30, 2020 at 1:00
  • 1
    \$\begingroup\$ Please can you add more information to your post. As currently it's unclear what you're asking for. Thank you. \$\endgroup\$
    – Peilonrayz
    Commented Jan 30, 2020 at 13:49

1 Answer 1

1
\$\begingroup\$

You might want to ask a more specific question on Stack Overflow if you don't know if it works.

In the meantime, you should catch the most specific exception you can, so except OSError instead of a bare except. Also, you should use exception code to mitigate a problem and continue, so more like:

try:
    shutil.rmtree('c:/guna/newCAT1')
    print("dir newCAT1 deleted")
except OSError:
    pass  # do nothing on this exception.
# continue with making the directory.  The exception statement is complete

or, if you read the documentation for shutil.rmtree:

shutil.rmtree('c:/guna/newCAT1', ignore_errors=True)
print("dir newCAT1 deleted")
os.mkdir('c:/guna/newCAT1')
print("dir newCAT1 created")
fileIN=open('c:/guna/newCAT1/secretMSG.txt','w' )
fileIN.writelines("the dog is green")
fileIN.close()
\$\endgroup\$
1
  • \$\begingroup\$ thank you for the code example. it gave me idea about how to write a python code. \$\endgroup\$ Commented Sep 29, 2020 at 14:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.