简体   繁体   中英

How to write script that edits every excel file inside a folder

I want to make a script that writes a certain text to the A1 cell of every excel file inside a folder. I'm not sure how to get Python to open every file one by one, make changes to A1, and then overwrite save the original file.

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()

I see following errors in your code:

You have an error in .endswith , it should be

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

ie it needs to be feed with tuple of allowed endings.

Your if lacks : at end and your indentation seems to be broken.

You should deliver one argument to .load_workbook and one argument to .save , ie name of file to read/to write.

I would iterate through the folder and use pandas to read the files as temporary data frames. From there, they are easily manipulable.

Assuming you are in the relevant directory:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM