Python: Xlsxwriter, Save a file after first save failed - python

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')

Related

How do I remove and then open a file for writing in python?

Here is some code.
sbfldr = input('Enter subfolder name: ')
try:
os.remove(os.path.join(sbfldr, 'Report.html'))
except:
print('Remove error. Please close the report file')
exit()
try:
fwrite = open(os.path.join(sbfldr, 'Report.html'),'a')
exit()
except:
print('Open error. Please close the report file')
exit()
The results I expect are
If an old version of 'Report.html' exists, then remove it.
Open a new 'Report.html' for writing.
When I search for this question I get lots of answers (to other questions). This is probably because the answer is very easy, but I just do not understand how to do it.
There's no need to remove the file when you can just empty it. File mode w will "open for writing, truncating the file first", and if the file doesn't exist, it will create it.
sbfldr = input('Enter subfolder name: ')
fname = os.path.join(sbfldr, 'Report.html')
with open(fname, 'w') as fwrite:
pass # Actual code here
BTW this uses a with-statement, which is the best practice for opening files. As well it ignores the bad error handling (bare except) and unnecessary exit() in your program.
Thanks to #furas for mentioning this in the comments
Try the following, using os.path.exists to check if the file exists, and os.remove to remove it if so:
import os
if os.path.exists("Report.html"):
os.remove("Report.html")
with open("Report.html", "w") as f:
pass #do your thing

failing to move file from input folder to error folder

I am trying to run a code where i am read files sheets. Issue i am facing is, if there is a file which has no sheet named SheetSum I am not able to move it to error location.
example:
def read_file(data_file):
# data_file = '\rr\ex.xlsx'
sheets = {}
try:
print("Reading file: "+data_file)
sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
return sheets
read_file(file)
shutil.move( file, dirpath +'\\processed_files')
Getting an error as:
[WinError 32] The process cannot access the file because it is being used by another process
Updates:
If finally is present, it specifies a cleanup handler. The try
clause is executed, including any except and else clauses. If an
exception occurs in any of the clauses and is not handled, the
exception is temporarily saved. The finally clause is executed. If
there is a saved exception it is re-raised at the end of the finally
clause. If the finally clause raises another exception, the saved
exception is set as the context of the new exception.
..More Here
Accepted Solution worked like charm.
Try closing the file before attempting to move it.
So something like
def read_file(data_file):
# data_file = '\rr\ex.xlsx'
sheets = {}
try:
print("Reading file: "+data_file)
sheets_file = open(data_file,'rb')
sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
finally:
sheets_file.close()
return sheets
read_file(file)
shutil.move( file, dirpath +'\\processed_files')
The problem is the file opens, is handed to the pandas method, and when an exception occurs, your file is never closed.
Adding a finally to your try except block ensures that your file is always closed.

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 !

Create new file only if it cannot be opened and read in Python using "with __ as"

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()

Open a file for writing

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.

Categories

Resources