Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haw to save the new result which are extracting from csv file in python?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading