【问题标题】:How to apply a python code to multiple Excel files in a folder如何将python代码应用于文件夹中的多个Excel文件
【发布时间】:2021-12-30 14:01:57
【问题描述】:

我是 Python 编程新手。我需要将代码应用于保存在同一文件夹中的多个 Excel 文件。我能怎么做?我尝试使用 os.listdir 但程序给了我一个错误,因为在目录中找不到文件。这是我写的代码:

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)

【问题讨论】:

    标签: python excel


    【解决方案1】:

    os.listdir() 只为您提供文件名,而不是完整路径。

    代替

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

    您需要将文件夹重新加入到路径中:

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

    【讨论】:

    • 太好了,非常感谢!
    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2018-01-23
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多