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)
>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)