Home > Software engineering >  creating a new file with a row in multiple csv in a csv
creating a new file with a row in multiple csv in a csv

Time:11-30

I have a Directory in which all the csv files(Date-wise) have a list of various fruits and there quantity I want a one(new)csv in which I get only one fruit(say apple's) data. I have tried the following code but it's not giving me the required output. Help Please. Thank you. Cheers.

list1.csv

| Name     | Qty |
| -------- | --- |
| apple    |15   | 
| apple    |50   |
| mango    |20   | 
| grapes   |49   |

list2.csv

| Name     | Qty |
| -------- | --- |
| apple    |25   | 
| apple    |50   |
| Banana   |34   |
| mango    |20   | 
| grapes   |49   |

list3.csv

| Name     | Qty |
| -------- | --- |
| apple    |125   | 
| apple    |530   |
| mango    |20   | 
| grapes   |49   |

I want a new.csv in which I want

| Name     | Qty |
| -------- | --- |
| apple    |15   | 
| apple    |50   |
| apple    |25   | 
| apple    |50   |
| apple    |125  | 
| apple    |530  |
import pandas as pd
import glob, os
path = ("E:/Data/Fdata")
all_files = glob.glob(path   "/*.csv")
li=[]
for filename in all_files:
    df=pd.read_csv(filename, index_col=None, header=0)
    ndf = df[df["Name"].str.contains("Apple")]
    li.append(ndf)
    ndf.to_csv("E:/Data/Fdata/onlyapple.csv", index=True)

CodePudding user response:

  1. Read all your csv files to a master DataFrame
  2. Filter on the "Name" you want and write to_csv
import os
import pandas as pd

master = pd.DataFrame()
for file in [f for f in os.listdir(".") if f.endswith("csv")]:
    master = master.append(pd.read_csv(file), ignore_index=True)
    
master[master["Name"].eq("apple")].reset_index(drop=True).to_csv("onlyapple.csv")
onlyapple.csv:
,Name,quantity,price
0,apple,15,500
1,apple,50,400
2,apple,15,500
3,apple,50,400
  • Related