0

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 !

6
  • 3
    can you please show the error ? Commented Dec 2, 2019 at 11:09
  • 3
    Which Python version are you using?
    – Fourier
    Commented Dec 2, 2019 at 11:09
  • I think you missed the function call fp.close() when pasting , also try to use context managers
    – dejanualex
    Commented Dec 2, 2019 at 11:16
  • 3
    An IOError is raised if the file can't be opened. file.close doesn't raise an IOError
    – void life
    Commented Dec 2, 2019 at 11:18
  • Do you have the correct rights to write to that location ? More info about context managers: book.pythontips.com/en/latest/context_managers.html
    – dejanualex
    Commented Dec 2, 2019 at 11:24

2 Answers 2

1

So if I understand it correctly, IOError is not catching exception but it is exploding. Did you try some more generic exception ('except Exception')?

Or you can try workaround with finally instead of except part:

finally:
    if not f.closed:
        # handle exception here
2
  • And check this stackoverflow.com/questions/53215714/… , maybe you are looking for 'EnvironmentError' and not 'IOError'.
    – Dolfa
    Commented Dec 2, 2019 at 12:25
  • Didn't work. I thought it would be obvious it's a IOError, as it displays a "IOError" when it doesn't catch the Exception. EnvironementError doesn't work neither.
    – Metapod
    Commented Dec 2, 2019 at 13:02
1

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 !

2
  • 1
    Probably the IOError exception is triggered in the moment of buffer-flush writing, i.e.: fp.write('%s' % buffer) , which is now covered by the exception handler. In your first try, only the file closing was covered inside the try-except clause. Commented Dec 2, 2019 at 15:47
  • Yes, maybe, I didn't think it would be "earlier".
    – Metapod
    Commented Dec 2, 2019 at 17:11

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