File handling with try and except 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()
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()