为什么输出csv文件不显示预期结果?

时间:2017-03-03 17:04:32

标签: python csv

import glob
from datetime import date
import csv
import numpy as np
import pandas as pd
from itertools import islice
path = 'C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/November/*.csv'
for fname in glob.glob(path):
    with open (fname) as f:
        readCSV = csv.reader ((islice(f, 24, None)), delimiter = ';')
        irrad_fore = []
        timestamp = []
        day = []
        month = []
        year = []
        for row in readCSV:
            irrad1 = row[4]
            time = row[3]
            d = row[2]
            m = row[1]
            y = row[0]

            irrad_fore.append(irrad1)
            timestamp.append(time)
            day.append(d)
            month.append(m)
            year.append(y)

            out = csv.writer(open('C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/forecast_11-2016.csv','w', newline=''), delimiter=';')
            for values in zip(year, month, day, timestamp, irrad_fore):
                 x = values
                 out.writerow(x)

为什么输出csv文件只包含最后几天的数据,而当我将变量x打印到屏幕时它包含整个月的数据?

1 个答案:

答案 0 :(得分:0)

编辑:

在我看来,你想要实现的目标(基本上连接所有文件?)是这样的:

path = 'C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/November/*.csv'

irrad_fore = []
timestamp = []
day = []
month = []
year = []

for fname in glob.glob(path):
    with open (fname) as f:
        readCSV = csv.reader ((islice(f, 24, None)), delimiter = ';')

        for row in readCSV:
            irrad1 = row[4]
            time = row[3]
            d = row[2]
            m = row[1]
            y = row[0]

            irrad_fore.append(irrad1)
            timestamp.append(time)
            day.append(d)
            month.append(m)
            year.append(y)

out = csv.writer(open('C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/forecast_11-2016.csv','w', newline=''), delimiter=';')
for values in zip(year, month, day, timestamp, irrad_fore):
    x = values
    out.writerow(x)

尽管直接编写csv文件而不将所有内容汇总到临时列表中可能会更好:

path = 'C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/November/*.csv'
out = csv.writer(open('C:/Users/Calum/AppData/Local/Programs/Python/Python35-32/Python Programs/Brunel Forecasts/forecast_11-2016.csv','w', newline=''), delimiter=';')

for fname in glob.glob(path):
    with open (fname) as f:
        readCSV = csv.reader ((islice(f, 24, None)), delimiter = ';')

        for row in readCSV:
            irrad1 = row[4]
            time = row[3]
            d = row[2]
            m = row[1]
            y = row[0]

            out.writerow([y,m,d,time,irrad1])