Clangorous Chimera
Clangorous Chimera

Reputation: 223

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

Upvotes: 5

Views: 4109

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140287

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.

Upvotes: 3

Related Questions