Home > Software engineering >  Haw to save the new result which are extracting from csv file in python?
Haw to save the new result which are extracting from csv file in python?

Time:12-23

I have the (M.csv) file contain many columns. I extract 2 columns from the (M.CSV) file by using DictReader, Now I want to save these 2 columns in New CSV file. I use data.to_csv(.....) but not working.

this is the code:

import pandas as pd
import csv
with open('M.csv', newline='') as f:
 data = csv.DictReader(f)
 print("I_CaIIHK",",", 'Swm')
 print("---------------------------------")
 for row in data:
    print(row['I_CaIIHK_err'],"," ,row['Swm'])
    
data.to_csv('New.csv',index=False)  
.............................................................
the code is run and I got the 2 columns but cannot saving in new csv file.
...........................................................................

And this is the error:

AttributeError: 'DictReader' object has no attribute 'to_csv'


[enter image description here](https://i.stack.imgur.com/vYZYS.jpg)

CodePudding user response:

It looks like you are trying to call the pandas.DataFrame.to_csv method on a csv.DictReader object (which is not a DataFrame). You should be able to read the CSV file into a DataFrame with the pandas.read_csv function, specifying only the columns you want with the usecols argument, then save the data with the pandas.DataFrame.to_csv method.

Then you don't need the csv library at all :).

Something like:

import pandas as pd

COLUMNS_TO_USE = ["I_CaIIHK_err", "Swm"]
PATH_TO_FILE = "./M.csv"
OUTPUT_FILE = "New.csv"

df = pd.read_csv(filepath=PATH_TO_FILE, usecols=COLUMNS_TO_USE)
df.to_csv(path_or_buf=OUTPUT_FILE)

CodePudding user response:

It looks like you are trying to save the data you have extracted from the M.csv file to a new CSV file using the to_csv function from the pandas library, but you are calling it on the DictReader object data rather than on a pandas DataFrame.

To save the data you have extracted to a new CSV file, you will need to first create a pandas DataFrame from the data using the pd.DataFrame function. You can then call the to_csv function on the DataFrame to save it to a new CSV file.

Here is an example of how you can do this:

import pandas as pd
import csv

# Extract the data from the M.csv file and store it in a list
data_list = []
with open('M.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        data_list.append({'I_CaIIHK_err': row['I_CaIIHK_err'], 'Swm': row['Swm']})

# Create a pandas DataFrame from the data
df = pd.DataFrame(data_list)

# Save the DataFrame to a new CSV file
df.to_csv('New.csv', index=False)

This code will read the M.csv file using a DictReader, extract the 'I_CaIIHK_err' and 'Swm' columns, create a pandas DataFrame from the data, and then save the DataFrame to a new CSV file called 'New.csv'.

  • Related