MChakir
MChakir

Reputation: 11

Python updating csv file

I am new in python world and I need help to update a csv file:

file.csv:

Number  Value  Value2
  1     3.14
  2     4.37
  3     5.23

I want to update Value2 with : value1 * 1000

I have tried this :

with open (iFile, "r") as csv_file:
    value1= []
    value2=[]

    fieldList = []

    csv_reader = csv.reader(csv_file)
    for row in csv_reader:    

        value1= row[2]
        value2= row[2]*1000

    fieldList.append([Number, value1, value2])

with open(iFile,"a") as file:             
    writer = csv.writer(file)
    writer.writerow(fieldList) 

f.close()

Upvotes: 0

Views: 510

Answers (1)

CMMCD
CMMCD

Reputation: 360

The most reliable approach would be to use the csv module since it will handle any special formatting needed for other fields. In your example code you are overwriting value1 and value2 on each iteration, you want to use the append function to add elements to a list.

import csv

result = []
with open('input.csv') as f:
    data = csv.DictReader(f)

    for x in data:
        x['Value2'] = float(x['Value']) * 1000
        result.append(x)

with open('output.csv', 'w+') as f:
    csv_writer = csv.DictWriter(f, fieldnames=result[0].keys())

    csv_writer.writeheader()
    csv_writer.writerows(result)

Upvotes: 1

Related Questions