Home > database >  Python/Pandas: Filter out files with specific keyword
Python/Pandas: Filter out files with specific keyword

Time:02-18

I am splitting a xlsm file ( with multiple sheets) into a csv with each sheet as a separate csv file. I want to save into csv files only the sheets whose name contain the keyword "Robot" or "Auto". How can I do it? Currently it is saving all sheets into csv files. Here is the code I am using -

import pandas as pd
xl = pd.ExcelFile('Sample_File.xlsm')
for sheet in xl.sheet_names:
    df = pd.read_excel(xl,sheet_name=sheet)
    df1.to_csv(f"{sheet}.csv",index=False)

CodePudding user response:

Can you try this?

import pandas as pd
import re

xl = pd.ExcelFile('Sample_File.xlsm')
for sheet in xl.sheet_names:
    if re.search('Robot|Auto', sheet):
        df = pd.read_excel(xl,sheet_name=sheet)
        df.to_csv(f"{sheet}.csv",index=False)
  • Related