通过 Python 更改 CSV 文件中的特定值 [英] Change specific value in CSV file via Python

查看:87
本文介绍了通过 Python 更改 CSV 文件中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来更改 CSV 文件列的特定值.例如我有这个 CSV 文件:

I need a way to change the specific value of a column of a CSV file. For example I have this CSV file:

"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50

并且我需要将127.0.0.2"行的值 23 更改为 30.

and I need to change the value 23 to 30 of the row "127.0.0.2".

我使用 csv 库:import csv

推荐答案

这是打开 csv 文件,更改内存中的值,然后将更改写回磁盘的解决方案.

This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.

r = csv.reader(open('/tmp/test.csv')) # Here your csv file
lines = list(r)

行的内容:

[['Ip', 'Sites'],
 ['127.0.0.1', '10'],
 ['127.0.0.2', '23'],
 ['127.0.0.3', '50']]

修改值:

lines[2][1] = '30'

行的内容:

[['Ip', 'Sites'],
 ['127.0.0.1', '10'],
 ['127.0.0.2', '30'],
 ['127.0.0.3', '50']]

现在我们只需要把它写回一个文件

Now we only have to write it back to a file

writer = csv.writer(open('/tmp/output.csv', 'w'))
writer.writerows(lines)

这篇关于通过 Python 更改 CSV 文件中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆