FileNotFoundError when load_workbook using the passed over filename

Question:

I def a function and passed over its argument from a for loop, and got the FileNotFoundError: [Errno 2] No such file or directory: ‘revenue.xlsx’.

The for loop works and the function also works when separately print them. So I am assuming something is wrong when passing over the argument.

Here’s my entire code.

import openpyxl as xl
from openpyxl.chart import Reference, BarChart
from pathlib import Path


def process_workbook(file_name):
    wb = xl.load_workbook(file_name)
    sheet = wb['Sheet1']
    for row in range(2, sheet.max_row + 1):
        cell = sheet.cell(row, 3)
        corrected_price = cell.value * 0.9
        corrected_price_cell = sheet.cell(row, 4)
        corrected_price_cell.value = corrected_price
    data = Reference(sheet, min_col=4, min_row=2, max_row=sheet.max_row)
    cats = Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row)

    chart = BarChart()
    chart.add_data(data)
    chart.set_categories(cats)
    sheet.add_chart(chart, 'F2')

    wb.save(file_name)
    return file_name


path = Path('/Users/yugao/Downloads/Python Tutorial Supplementary Materials')
for file in path.glob('*.xlsx'):
    filename = file.name
    process_workbook(filename)

here’s my error:

Traceback (most recent call last):
  File "/Users/yugao/PycharmProjects/HelloWorld/app.py", line 33, in <module>
    process_workbook(filename)
  File "/Users/yugao/PycharmProjects/HelloWorld/app.py", line 7, in process_workbook
    wb = xl.load_workbook(filen_ame)
  File "/Users/yugao/PycharmProjects/HelloWorld/venv/lib/python3.10/site-packages/openpyxl/reader/excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "/Users/yugao/PycharmProjects/HelloWorld/venv/lib/python3.10/site-packages/openpyxl/reader/excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "/Users/yugao/PycharmProjects/HelloWorld/venv/lib/python3.10/site-packages/openpyxl/reader/excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/zipfile.py", line 1240, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'revenue.xlsx'

Asked By: gaoyu

||

Answers:

You need to supply the path to the file as well (me thinks).

filename=str(path)+'/'+filename
Answered By: Kilian
# Define path to excel file
path = os.path.dirname(os.path.abspath(__file__))

# Define filename
filename=str(path)+'/'+filename

The above code snippet fixed the Exception has occurred: com_error issue I was running into.

Answered By: Harminder Nijjar
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.