简体   繁体   English

Python更新csv文件

[英]Python updating csv file

I am new in python world and I need help to update a csv file:我是 python 世界的新手,我需要帮助来更新 csv 文件:

file.csv:文件.csv:

Number  Value  Value2
  1     3.14
  2     4.37
  3     5.23

I want to update Value2 with : value1 * 1000我想用: value1 * 1000更新Value2

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

The most reliable approach would be to use the csv module since it will handle any special formatting needed for other fields.最可靠的方法是使用 csv 模块,因为它将处理其他字段所需的任何特殊格式。 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.在您的示例代码中,您将在每次迭代时覆盖 value1 和 value2,您希望使用append函数将元素添加到列表中。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM