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

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

问题描述

我需要更改csv文件列的具体值的方法。例如我有csv文件:

I need the way to change specific value of the column of csv file. For example I have 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 value 23 to 30 of the "127.0.0.2".

我使用csv库:import csv

I use csv library: import csv

感谢任何帮助,因为我是Python的新人。谢谢!

Appreciate any help as I'm new in Python. Thanks!

推荐答案

这是打开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 = [l for l in 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天全站免登陆