簡體   English   中英

python寫入csv文件

[英]python write to a csv file

我有一個點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]})

您必須更改打開文件的方式-模式“ 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()
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM