0

I am new in programming with Python. I need to apply a code to multiple Excel files saved in the same folder. How can I do? I tried with os.listdir but the program gives me an error for not finding the file in the directory. Here is the code that I wrote:

import openpyxl as xl

from openpyxl.chart import ScatterChart, Reference, Series

import os

folder = r"C:\\Users\\PycharmProjects\\Project\\output"

for file in os.listdir(folder):

    wb = xl.load_workbook(file)
    sheet = wb["Sheet"]
    for row in range(42, sheet.max_row + 1):
        cell = sheet.cell(row, 5)
        cell_num = float(cell.value)
        cell_num_sheet = sheet.cell(row, 5)
        cell_num_sheet.value = cell_num
        cell1 = sheet.cell(row, 8)
        cell1_num = float(cell1.value)
        cell1_num_sheet = sheet.cell(row, 8)
        cell1_num_sheet.value = cell1_num
        chart1 = ScatterChart()
        chart1.title = "Speed of sound [m/s] vs Temperature [°C]"
        chart1.y_axis.title = "Speed of sound [m/s]"
        chart1.x_axis.title = "Temperature [°C]"
        xvalues = Reference(sheet, min_col=8, min_row=42, max_row=sheet.max_row)
        yvalues = Reference(sheet, min_col=5, min_row=42, max_row=sheet.max_row)
        series = Series(values=yvalues, xvalues=xvalues, title="1.5%")
        chart1.series.append(series)
        sheet.add_chart(chart1, "t42")
    wb.save(file)

1 Answer 1

1

os.listdir() gives you just filenames, not full paths.

Instead of

for file in os.listdir(folder):
    wb = xl.load_workbook(file)

you'll need to join the folder back into the path:

for file in os.listdir(folder):
    wb = xl.load_workbook(os.path.join(folder, file))
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.