Search code examples
pythonioerror

Python - close file and IOError


I'm writing a prog which writes data into a file, and each hour a new file is generated, with a precise title. When the storage is full, it either stops the application, or deletes the oldest file created in the folder.

fp = open (fileNamePath, 'a')
fp.write('%s' % buffer)
try:
    fp.close()
except IOError:
    # delete file or close app

But when it comes to the except, it just skips it, and display IOError.

Thanks !


Solution

  • I looked for solution on Google, and someone suggested to use :

    try:
        with open(filePath,'a') as fp:
            fp.write('%s' % buffer)
    
    except IOError as exc:
        # Handling exception
    

    Well I don't get why but it works that way.

    Thanks all !