Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xlsx Writer not creating excel file but not creating an error either

When I run this in python, I get no errors. However, when I check the folder in which I have my program saved, no excel file is created. Not sure what I did wrong.

import xlsxwriter
workbook = xlsxwriter.Workbook("result.xlsx")
worksheet = workbook.add_worksheet()

worksheet.write('A1','plz work')

workbook.close()
like image 671
Clangorous Chimera Avatar asked Oct 17 '22 10:10

Clangorous Chimera


1 Answers

Depending on your IDE or the way you're running your script, the current directory can be anything but not necessarily the directory where the script is located.

To create the file where the script is located, a good trick is this:

import os
workbook = xlsxwriter.Workbook(os.path.join(os.path.dirname(os.path.abspath(__file__)),"result.xlsx"))

__file__ is the path of your current script, taking the directory name & joining to file base name creates the absolute path of your output file. I used os.path.abspath on it because it can return a basename (depending on how it is run, and as opposed to Unix command dirname, os.path.dirname of a basename doesn't return . but empty string, so the os.path.join fails in that case.

like image 109
Jean-François Fabre Avatar answered Oct 22 '22 10:10

Jean-François Fabre