如何解决csv输出文件错误?

时间:2018-01-28 10:57:36

标签: python python-3.x csv export-to-csv

csv输入文件:

c1,c2,c3,c4,c5,c6    
16,28-Sep-17,9700,291.8,291.8,9964.4    
17,28-Sep-17,9700,186.3,186.3,9872.6    
18,28-Sep-17,9700,166.6,166.6,9871.5    
24,28-Sep-17,9800,227.5,227.5,9952.2  
25,28-Sep-17,9800,202.55,202.55,9916.2

代码:

from itertools import zip_longest
from collections import defaultdict
import csv

models = defaultdict(list)

with open('outpuop.csv') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        # Convert c3 to c6 into floats
        row[2:6] = map(float, row[2:6])

        if row[2] > row[5]:
            if row[4] != 0:
                TV = row[4] - (row[2] - row[5])
                models[row[2]].append(TV)
            else:
                TV = row[3] - (row[2] - row[5])
                models[row[2]].append(TV)
        else:
            tv = row[4]
            models[row[2]].append(tv)


columns = sorted(models.keys())
data = [[int(column)] + ["{:.2f}".format(v) for v in models[column]] for 
     column in columns]

with open('out1.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerows(zip_longest(*data, fillvalue=''))

当我编译时,我有这个:

  

TypeError:需要类似字节的对象,而不是'str'

如何解决?

1 个答案:

答案 0 :(得分:0)

您以二进制模式打开文件。因此,它需要字节,而不是字符串。

请改为尝试:

with open('out.csv', 'w', newline='') as f_output:

Examples