Home > Net >  How do i delete a particular sheet in a flat file with python?
How do i delete a particular sheet in a flat file with python?

Time:05-03

Im trying to write a loop that browses through my directory to find a file that starts with a particular filename('TVC') and deletes a specific sheet within that file. In the below case 'Opt-Ins' is the name of one of the sheets I want to delete

My attempt-

import os
path = 'C:/Users/grr/Desktop/autotranscribe/python/Matching'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         'TVC' in i]
    
    from openpyxl import load_workbook

wb = load_workbook(files)
if 'Opt-Ins' in wb.sheetnames:
    wb.remove(wb['Opt-Ins'])
wb.save(files)

TypeError: expected str, bytes or os.PathLike object, not list

I just want to delete a specific sheet. how do I do this?

CodePudding user response:

The problem is that you are trying to call load_workbook on a list of filenames:

wb = load_workbook(files)

You need to loop over the files, and run your code on each file in the loop:

for filename in files:
    wb = load_workbook(filename)
    ...  # rest of your code here

It looks like you do understand loops, so I assume this was just an oversight. Don't forget to take breaks when programming. In my experience, the chance of making a mistake like this greatly increases when I work for too long without a break.

  • Related