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? Commented Dec 2, 2019 at 11:09
  • I think you missed the function call fp.close() when pasting , also try to use context managers 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 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 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 
Sign up to request clarification or add additional context in comments.

2 Comments

And check this stackoverflow.com/questions/53215714/… , maybe you are looking for 'EnvironmentError' and not 'IOError'.
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.
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 Comments

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.
Yes, maybe, I didn't think it would be "earlier".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.