【问题标题】:python write to a csv filepython写入一个csv文件
【发布时间】:2015-04-20 12:54:47
【问题描述】:

我有一个点 Q(元组),每次调用函数时都会创建它。如何将新点 Q 写入 csv 文件,使得第一列是 x 坐标,第二列是 y 坐标,第三列是 z 坐标而不覆盖文件?谢谢你

with open('points.csv', 'w') as csvfile:
    fieldnames = ['x', 'y','z']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for val in q:
        writer.writerow({'x':q[0] , 'y': q[1], 'z': q[2]})

【问题讨论】:

  • 你的问题是什么?
  • 我已经更改了帖子。请看一下
  • 如果要向该文件写入新行,请在打开文件时使用“a+”而不是“w”。

标签: python csv writing


【解决方案1】:

您必须更改打开文件的方式 - 模式“w”始终代表创建/截断文件。只需使用“a”(代表“append”):

with open('points.csv', 'a') as csvfile:
     ...

当然,如果文件已经存在,你不希望每次重新打开它时都重新写入标题 - 因此,你可以在打开文件之前验证文件是否存在:

import os
file_exists = os.path.exists("points.csv")
with ... as csvfile:
    writer = ...
    if not file_exists:
        writer.writeheader()
    ...

【讨论】:

  • 伟大的伙伴,干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
相关资源
最近更新 更多