在Python中修改csv文件

发布于 2024-10-01 12:04:29 字数 787 浏览 1 评论 0原文

所以我有一个 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,192.168.0.8,192.168.0.9,192.168.0.10

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

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

这将打印:

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
...

然后将其写入末尾,我尝试了多种方法,包括:

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

但是,这会用新条目替换整个文件。然后,我尝试循环遍历现有记录并将它们添加到新文件中,但这将 IP 按其 . 分开!我在这里错过了什么吗? csv 读取器/写入器肯定有修改选项吗?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻许诺言 2024-10-08 12:04:29

为什么不添加一个新行呢?

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

Why don't you just append a new row?

fd = open('file.csv','a')
fd.write(yourCsvRowWithNewIP)
fd.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文