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 !
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
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 !
Related
I would like to try opening a file to read, and only if this fails, overwrite it or create a new file. I know it can be done using try, except, finally methodology, but I was wondering if there was a more elegant way to do it with the with & as keywords.
try:
f = file.open("file","r")
try:
parse_file(f)
finally:
f.close()
except CustomError as e:
overwrite_file(e)
except FileNotFoundError:
create_file()
except:
handle_errors()
I'm processing a file and then want to remove it. My code ends with:
...
tar.extractall(dir=...)
tar.close()
os.remove(filename)
This sometimes causes an error:
[Errno 16] Resource busy: 'skyimage/sgptsiskyimageC1.a1.20160415.000000.jpg.tar'
I was able to work around this by telling Python to keep trying until it works:
while True:
try:
os.remove(filename)
break
except OSError as err:
continue
Is there a more Pythonic way to do this?
I have a function that takes a source file containing times (a csv file), reads it, then sorts the lines in order and writes them in a destination file. However, if the source csv file does not exist, I need to raise a FileNotFoundError. I've raised exceptions before, for example, if a parameter wasn't an integer I had to raise ChangeParameterError by using:
class ChangeParameterError(Exception):
pass
and then raising that in my function.
For my problem, my function is as follows:
def times(src,dst):
s = open(src,'r')
d = open(dst,'w')
lines = s.readlines()
s.close()
lines.sort()
for i in lines:
print((str(i).strip()), file = d)
d.close()
Any help is appreciated!
If the specified file is not found, the FileNotFoundError will be raised automatically by the open call when trying to open the file.
The exception is automatically raised by python. But you may need to wrap your open with a try-except to catch the exception without breaking your code:
try:
s = open(src,'r')
except FileNotFoundError:
print('file not found')
When i try to open a file, even if it is not opened until that moment, it gives an error about that and therefore i cant write on it. Here is my python code:
try:
myfile = open("SolvedFromFile.xls", "r+")
except IOError:
mesaj=u"Açık olan nokta listesini kapatın!"
wx.MessageBox(mesaj, u"UYARI")
What can cause that?
Thanks in advance.
e.g. you script has no rights to read...rarely happens on your own computer. most seen on productive environment.
or file not found(?)
You have to check the caught exception to see what the cause is:
try:
myfile = open(...)
except IOError as (errno, strerror):
print 'Error code %d: %s' % (errno, strerror)
Give the full address in the open() method. Also check if the file exists or not and your have rights to that location. All the best.
With having the with statement, is there ever a need to open a file/check for exceptions/do manual closing of resources, like in
try:
f = open('myfile.txt')
for line in f:
print line
except IOError:
print 'Could not open/read file'
finally:
f.close()
Your current code tries to handle the exception of the file not being found, or of insufficient access permissions etc., which a with open(file) as f: block wouldn't have done.
Also, in this case, the finally: block would have raised a NameError since f wouldn't have been defined.
In a with block, any exception (of whatever kind, maybe a division by zero in your code) that occurs within the block will still be raised, but even if you don't handle it, your file will always be closed properly. That's something entirely different.
What you want is probably:
try:
with open("myfile.txt") as f:
do_Stuff() # even if this raises an exception, f will be closed.
except IOError:
print "Couldn't open/read myfile.txt"