Home > Software engineering >  How to search certain column title with a certain name and save it to new path
How to search certain column title with a certain name and save it to new path

Time:07-25

I am trying to search for anything that starts with "customers" in an excel file and save it to a new file path.

For example: A1 has :customer_id, B1 has:store_location C1 has: customer_purchase, I just want to save customer_id and customer_purchase to a new path.

so far this is what I have tried. Besides that, I don't know how to approach this.

customer_data=[]

if ws.cell=="customer":
   customer_data.append(ws.cell)
            
wb.save(new_path)

CodePudding user response:

This is relatively simple to do with pandas.

import pandas as pd

data = pd.read_excel('customer_stuff.xlsx') #load the file
names = data.columns.tolist() #create a list of the columnnames
new_data = pd.DataFrame()

for name in names:
    if name.lower()[:len('customer')] == 'customer': #checks if the start of the string of length of 'customer' (8 chars) is 'customer'
        new_data[name] = data[name] #add the respective columns to the new data/file
        
new_data.to_excel('your//path.xlsx', index=False) #save the file

This is the simplest and most elegant way in my opinion.

  • Related