使用Python填充csv文件

时间:2016-06-04 20:51:35

标签: python csv

以下代码段创建了一个CSV文件,但每隔一行都是空白的。如何防止这些换行?

import datetime
import time
import csv

i = 0
while i < 10:
    TempProbe = "78.12" 
    CurrentTime = time.strftime("%x")
    CurrentDate = time.strftime("%I:%M:%S")
    stringAll = TempProbe + "," + CurrentTime + "," + CurrentDate
    print(stringAll)
    file = open("outFile.csv", "a")
    csvWriter = csv.writer( file )
    csvWriter.writerow( [TempProbe, CurrentTime,CurrentDate] )
    file.close()
    i = i + 1
    time.sleep(1)

4 个答案:

答案 0 :(得分:5)

这可能是因为默认行终止符是'\r\n'。您可以通过将lineterminator='\n'传递到csv.writer对象来更正此问题,如下所示:

csvWriter = csv.writer(file, lineterminator='\n')

P.S。将此行移出while循环,以避免破坏和重新创建文件编写器对象。

答案 1 :(得分:1)

您需要为csvWriter设置lineterminator,如下面的代码所示。

csvWriter = csv.writer(file, lineterminator='\n')

有关原因的解释,请参阅:CSV file written with Python has blank lines between each row

答案 2 :(得分:0)

您只需使用open函数编写csv文件:

file = open("outFile.csv", "a")
file.write(stringAll+'\n')

此外,您应该将文件openclose功能移出循环。

答案 3 :(得分:0)

使用它:&#39; ab&#39; vs&#39; a&#39;,写二进制应该解决问题

file = open("outFile.csv", "ab")
csvWriter = csv.writer(file, lineterminator='\n' )

或者你不需要在每次写作时打开/关闭:

file      = open("outFile.csv", "ab")
csvWriter = csv.writer(file, lineterminator='\n' )

i = 0
while i < 10:
    TempProbe = "78.12" 
    CurrentTime = time.strftime("%x")
    CurrentDate = time.strftime("%I:%M:%S")
    stringAll = TempProbe + "," + CurrentTime + "," + CurrentDate
    print(stringAll)
    csvWriter.writerow( [TempProbe, CurrentTime,CurrentDate] )   
    i = i + 1
    time.sleep(1)

file.close()
相关问题