openpyxl save workbook to file with path

Question:

I use Openpyxl in Python to write some data in an Excel file using Workbook.
When I want to save the workbook to a file, I can only provide a filename argument, so I can not write files in other directories.

here is my sample code:

import openpyxl

file_name = "sample.xlsx"

wb = openpyxl.Workbook()

# writing some data to workbook

wb.save(filename=file_name)

I have checked the documentation via this link and found nothing more.

Python: 3.10.7

Openpyxl: 3.0.10

Can you help me provide workarounds to solve this problem?

Asked By: Masoud

||

Answers:

Oh it’s not hard and completely as others Python methods

So just use the full file path

import openpyxl

file_path = "/your/path/here/sample.xlsx"

wb = openpyxl.Workbook()

wb.save(filename=file_path)
Answered By: di.bezrukov

Thanks to @di-bezrukov answer I changed the code like this and it works fine.

import os
import openpyxl

file_path = "some_directory"
file_name = "sample.xlsx"

wb = openpyxl.Workbook()

# writing some data in the workbook

wb.save(filename=os.path.join(file_path, file_name))
Answered By: Masoud
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.