在Python中修改csv文件 [英] Amend a csv file in Python

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

问题描述

所以我有一个CSV文件,其中有一堆IP:

  192.168.0.1,192.168.0.2,192.168 .0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,19​​2.168.0.8,192.168.0.9,192.168.0.10 

我想在这个csv文件的末尾添加一个新的ip。目前我使用这个代码读取数据:

  requests = csv.reader(open(file.csv, rb))
请求中的请求:
for ip in request:
printIn List:+ str(ip)
/ pre>

这将打印:

 在列表中:192.168。 0.1 
在列表中:192.168.0.2
在列表中:192.168.0.3
在列表中:192.168.0.4
在列表中:192.168.0.5
...

然后写一个到最后我试过很多方法,包括:

  requestWriter = csv.writer(open(file.csv,w))
requestWriter.writerow([192.168。 0.X])

然而,这将用新条目替换整个文件。然后,我尝试循环通过现有的记录,并将它们添加到新文件,但这将IP分开的他们的!我在这里缺少什么?



感谢

解决方案

为什么不添加新行?

  fd = open('file.csv' a')
fd.write(yourCsvRowWithNewIP)
fd.close()


So I have a CSV file with a bunch on IP's in it:

192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,192.168.0.8,192.168.0.9,192.168.0.10

And I would like to add a new ip to the end of this csv file. Currently I am using this code to read in the data:

requests = csv.reader(open("file.csv", "rb"))
for request in requests:
    for ip in request:
        print "In List: " + str(ip)

This will print:

In List: 192.168.0.1
In List: 192.168.0.2
In List: 192.168.0.3
In List: 192.168.0.4
In List: 192.168.0.5
...

And then to write one to the end I've tried many methods, including this:

requestWriter = csv.writer(open("file.csv", "w"))
requestWriter.writerow(["192.168.0.X"])

This however replaces the whole file with the new entry. I then tried to loop through existing records and add them to the new file but this split the IP's up by their .'s! Am I missing something here? Surely there is an amend option for the csv reader/writer?

Thanks

解决方案

Why don't you just append a new row?

fd = open('file.csv','a')
fd.write(yourCsvRowWithNewIP)
fd.close()

这篇关于在Python中修改csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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