Open a file for writing - python

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.

Related

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 !
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 !

Python: Xlsxwriter, Save a file after first save failed

Sometimes I am trying to save a xlsx workbook and I have the file open. I do a lot of processing before, so if the file save fails for something as simple as the worksheet being open, I have to run the whole script again.
Wanted to do something like this but it doesn't seem to save the new file, even when I close the old one and retry. I'm guessing this is something to do with the wb object going away.
Is there a way to fix this?
import xlsxwriter,datetime,time
wb=xlsxwriter.Workbook('test.xlsx')
ws=wb.add_worksheet('test')
ws.write_row(0,0,['aaaa',str(datetime.datetime.now())])
try:
wb.close()
except IOError :
print('save error, please close file, will retry in 10')
time.sleep(10)
wb.close()
From AIG's answer, this works great, Thank you:
wb=xlsxwriter.Workbook('test.xlsx')
ws=wb.add_worksheet('test')
ws.write_row(0,0,['aaaa',str(datetime.datetime.now())])
for i in range(3):
try:
test=open('test.xlsx','w')
except IOError :
if i!=2:
print('save error')
time.sleep(5)
try:
wb.close()
except IOError:
print('could not save file')

os.remove claims a file is "busy" for a while

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?

File is automatically closed

f1 = open("D:/Studies/Python/IDEs/PyCharm/Basics/Basics.py", 'r')
print(next(f1))
The error is:
ValueError: I/O operation on closed file.
I'm trying to access this file from a program which is located in another path:-("D:\Studies\Python\IDEs\PyCharm\File IO\File_IO_Basics.py")
Is that a problem?
If there's any other problem please mention.
Most probably your file has not been opened successfully. Try to include a try ... except near your open command and make sure that way that the file has really been opened:
try:
f1 = open("D:/Studies/Python/IDEs/PyCharm/Basics/Basics.py", 'r')
print "File has been opened"
print(next(f1))
except:
print "File has not been opened"
You could also check whether your file exists at that path using:
import os
if os.path.exists("C:\..."):
print "File exists"

Python with statement - is there a need for old-style file handling any more?

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"

Categories

Resources