如何在python中以CSV格式编写输出文件? [英] How to write output file in CSV format in python?

查看:1905
本文介绍了如何在python中以CSV格式编写输出文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将输出文件作为CSV文件写入,但得到错误或不是预期的结果。我使用的是Python 3.5.2和2.7。

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.

在Python 3.5中遇到错误:

Getting error in Python 3.5:

wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'

在Python 2.7中,我得到了所有列的结果。

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

预期结果:

与输入文件格式相同的输出文件。

Expected Result:
An output file same format as the input file.

代码:

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]) 

如果我使用 resultFile = open(out.csv,w),我得到一行额外的输出文件。

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.

推荐答案

在Python 3上, csv 需要以文本模式打开文件,而不是二进制模式。从您的文件模式中删除 b 。你真的应该使用 newline =''

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')])


b $ b

我也剥离了 f1 (只是为了删除换行)的行,并将该行放在列表中; csv.writer.writerow 需要一个有列而不是单个字符串的序列。

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.

引用 csv.writer() documentation

Quoting the csv.writer() documentation:


如果 csvfile 是一个文件对象,应该用 newline ='' [1]。 [...] 所有其他非字符串数据在写入之前用 str()进行字符串化。

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]如果未指定 newline ='',则不会正确解释嵌入在引用字段中的换行符, $ c> \r\\\
linendings写入额外的 \r 将被添加。指定 newline =''应该是安全的,因为csv模块有自己的( universal )换行处理。

[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.

这篇关于如何在python中以CSV格式编写输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆