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?
Related
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 !
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 am running the following code very often to write to files from Python using the following:
def function():
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
fifo = open(file, 'w')
if (os.path.isfile(file) and os.access(file, os.W_OK)):
fifo.write("stuff")
fifo.close()
else:
time.sleep(1)
function()
Unfortunately, I get the following error (not all the time):
IOError: [Errno 2] No such file or directory
This is self-explanatory, but I do not understand then why all the precautions do not work, like isfile or access..W_OK ? How do I avoid having this issue?
Also, the slower the machine, the less often the error is encountered.
See also "LBYL vs EAFP in Java?":
Instead of checking if the action is ok (LBYL), you should do an EAFP approach. Just do what you want to do and check if it has worked correctly.
Besides, better don't call function() recursively, it might lead to a stack overflow if the error persists.
Better do
def function():
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
while True:
try:
with open(file, 'w') as file: # automatically closes...
file.write("some stuff")
except IOError, e:
time.sleep(1)
continue
break # the while loop
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"