correct way to catch exception with Python 'with' statement

g thakuri gbpal13 at gmail.com
Mon Nov 28 00:52:50 EST 2016


Dear Python friends,

Any suggestion on how to add exception and make the below program look
better  ,  I am using Python 2.7 and Linux

--------------------------------------------------------------------------------------------

def create_files_append():
    """  """
    try:
        os.makedirs(QA_TEST_DIR)
    except:
        raise OSError("Can't create directory (%s)!" % (QA_TEST_DIR))

    # Create few files and write something
    for i in range(1000):
        with open(os.path.join(QA_TEST_DIR,"filename%d" %i),'w') as f:
             f.write("hello")

    # Append the files
    for i in range(1000):
        with open(os.path.join(QA_TEST_DIR,"filename%d" %i),'w') as f:
             f.write("hello")

    return True

-----------------------------------------------------------------------------------------------

What will be the best  way to catch the exception in the above program  ?
Can we replace both the  with statement in the above program with something
like below

try:
    for i in range(1000):
               with open(os.path.join(QA_TEST_DIR,"filename%d" %i),'w') as f:
                   f.write("hello")
except IOError as e:
    raise

Regards,
PT



More information about the Python-list mailing list