1

I have a CSV file named samplecsv that has 4 fields A,B,C,D as follows:

[a1,b1,c1,2]

[a2,b2,c2,2]

[a3,b3,c3,2]

I need to update field D from '2' to '9' for all row.How can I do it. I try the code as follows,but did not work.

import csv
f = open('C:/samplecsv.csv', 'w')
writer.writerow({'D':'9'})
f.close()
PHE
  • 63
  • 8
  • Welcome to Stack Overflow, your question is unclear, Please read [**How to Ask a good question**](http://stackoverflow.com/help/how-to-ask) and find out how to use this site [**taking the tour**](http://stackoverflow.com/tour) – Vickel Dec 25 '17 at 02:23
  • @Vickel ,OK ! I try it later .Many thanks! – PHE Dec 25 '17 at 07:16

1 Answers1

0

you can use pandas instead of csv

import pandas as pd
df = pd.read_csv("C:/samplecsv.csv")
df["D"].replace(2,9, inplace=True)
df.to_csv("C:/samplecsv.csv",index=False)
Emmet B
  • 4,321
  • 5
  • 30
  • 44
  • When I write back to CSV file ,It will add a column having sequence value 0,1,2,3,4.... ;So the CSV file will be [0,a1,b1,c1,9],[1,a2,b2,c2,9],[2,a3,b3,c3,9]. How can I avoid the sequence value when writing to CSV file? 3Q~ – PHE Dec 30 '17 at 03:36
  • I got the answer from another question on Stack Overflow .https://stackoverflow.com/questions/16923281/pandas-writing-dataframe-to-csv-file – PHE Dec 30 '17 at 04:50