【问题标题】:How to write script that edits every excel file inside a folder如何编写编辑文件夹内每个excel文件的脚本
【发布时间】:2019-02-05 16:31:48
【问题描述】:

我想制作一个脚本,将特定文本写入文件夹内每个 excel 文件的 A1 单元格。我不确定如何让 Python 一个一个地打开每个文件,对 A1 进行更改,然后覆盖保存原始文件。

import os
import openpyxl

os.chdir('C:/Users/jdal/Downloads/excelWorkdir')
folderList = os.listdir()
for file in in os.walk():
    for name in file:
        if name.endswith(".xlsx" and ".xls")
        wb = openpyxl.load_workbook()
        sheet = wb.get_sheet_by_name('Sheet1')

sheet['A1'] = 'input whatever here!'
sheet['A1'].value
wb.save()

【问题讨论】:

  • 您目前拥有的代码有什么问题?您是否收到错误或与预期不同的输出?
  • 我想知道如何让 python 保存到文件夹中的每个文件而不是按名称打开一个文件,即 wb = openpyxl.load_workbook()

标签: python excel directory


【解决方案1】:

我在您的代码中看到以下错误:

.endswith有错误,应该是

name.endswith((".xlsx",".xls"))

即它需要以允许结尾的tuple 提供。

你的if最后缺少:,你的缩进似乎被破坏了。

您应该将一个参数传递给.load_workbook,并将一个参数传递给.save,即要读取/写入的文件名。

【讨论】:

    【解决方案2】:

    我会遍历文件夹并使用 pandas 将文件作为临时数据框读取。从那里,它们很容易被操纵。

    假设你在相关目录中:

    import pandas as pd
    import os
    
    files = os.listdir()
    
    for i in range(len(files)):
        if files[i].endswith('.csv'):
    
            # Store file name for future replacement
            name = str(files[i])
    
            # Save file as dataframe and edit cell
            df = pd.read_csv(files[i])
            df.iloc[0,0] = 'changed value'
    
            # Replace file with df
            df.to_csv(name, index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-15
      • 2013-09-01
      • 2011-06-14
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多