简体   繁体   English

使用python将每个结果保存在换行符中的csv文件中

[英]Saving each result on a new line to a csv file, using python

I've been trying to create a csv file using python and save a new date on a new row. 我一直在尝试使用python创建一个csv文件,并将新日期保存在新行上。 My intention is to replicate the shell output(shown below), in csv file. 我的意图是在csv文件中复制shell输出(如下所示)。 However the output I get is only saving the last result and iterating through one date(shown in the csv output below). 但是我得到的输出只是保存最后的结果并迭代一个日期(如下面的csv输出所示)。 I'm sure there's an error in my approach but I'm stumped. 我敢肯定我的方法有错误,但是我很沮丧。 thanks in advance. 提前致谢。

from datetime import timedelta, date
import csv

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = date(2014, 12, 28)
end_date = date(2015, 1, 10)

for single_date in daterange(start_date, end_date):
    new_date = single_date.strftime("%Y-%m-%d")
    with open('output.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(new_date)

shell output csv output 外壳输出 csv输出

When you open a file with w mode, python truncates the file. 当您使用w模式打开文件时,python会截断该文件。 You should open it only once: 您只应打开一次:

with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    for single_date in daterange(start_date, end_date):
        new_date = single_date.strftime("%Y-%m-%d")
        writer.writerow(new_date)

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

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