python输出如何加单位,如何在python中以CSV格式编写输出文件?

I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.

Getting error in Python 3.5:

wr.writerow(var)

TypeError: a bytes-like object is required, not 'str'

and

In Python 2.7, I am getting all column result in one column.

Expected Result:

An output file same format as the input file.

Code:

import csv

f1 = open("input_1.csv", "r")

resultFile = open("out.csv", "wb")

wr = csv.writer(resultFile, quotechar=',')

def sort_duplicates(f1):

for i in range(0, len(f1)):

f1.insert(f1.index(f1[i])+1, f1[i])

f1.pop(i+1)

for var in f1:

#print (var)

wr.writerow([var])

If I am using resultFile = open("out.csv", "w"), I get one row extra in the output file.

If I am using above code, getting one row and column extra.

解决方案

On Python 3, csv requires that you open the file in text mode, not binary mode. Drop the b from your file mode. You should really use newline='' too:

resultFile = open("out.csv", "w", newline='')

Better still, use the file object as a context manager to ensure it is closed automatically:

with open("input_1.csv", "r") as f1, \

open("out.csv", "w", newline='') as resultFile:

wr = csv.writer(resultFile, dialect='excel')

for var in f1:

wr.writerow([var.rstrip('\n')])

I've also stripped the lines from f1 (just to remove the newline) and put the line in a list; csv.writer.writerow wants a sequence with columns, not a single string.

If csvfile is a file object, it should be opened with newline='' [1]. [...] All other non-string data are stringified with str() before being written.

[1] If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值