简体   繁体   English

每次仅在CSV文件中追加一行

[英]Append only 1 row to CSV file each time

I use: 我用:

f = open("my_file.csv", "a")
writer = csv.writer(f)
writer.writerow(['one', 'two'])

But instead of appending a new row after the last row, it appends 2 new rows: an empty one and then the required one "one| two". 但是,它没有在最后一行之后添加新行,而是添加了2个新行:一个空行,然后是所需的“一|二”。 What is the reason for that? 是什么原因呢?

I find it easier to use with open() when writing to csv files. 我发现在写入csv文件时,更容易with open()使用。 The documentation can be found here . 该文档可在此处找到。 I can reproduce the problem you had on my machine, but the following code does not produce an empty line after each new line is appended. 我可以重现您在计算机上遇到的问题,但是在添加新行之后,以下代码不会产生空行。

import csv

with open('my_file.csv', 'a', newline='') as csvfile:      
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(['one', 'two'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM