csv writer预期的类似字节和行之间的空间 [英] csv writer expected byte like and space between rows

查看:71
本文介绍了csv writer预期的类似字节和行之间的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个CSV文件合并为一个。但是我在每一行之间都留有空格。

I'm trying to combine several CSV files into one. But I'm getting a space between each row.

我读过某个地方,必须在 filewriter = csv.writer(open ( output.csv, w))

I read somewhere I had to change w to wb in filewriter = csv.writer(open("output.csv", "w"))

但这给我以下错误:

Traceback (most recent call last):
  File "C:\Users\Rasmus\workspace\Portfolio\src\Companies.py", line 33, in <module>
    collect()
  File "C:\Users\Rasmus\workspace\Portfolio\src\Companies.py", line 31, in collect
    Write.UpdateCSV(lst)
  File "C:\Users\Rasmus\workspace\Portfolio\src\Write.py", line 11, in __init__
    filewriter.writerows(lst)
TypeError: a bytes-like object is required, not 'str'

我不确定为此,作为我能找到的唯一解决方案,我又遇到了另一个错误。

I'm not sure what to make of this, as the only solution I could find gave me another error.

还有其他方法可以消除行之间的空间吗?

Are there any other way to get rid of the space between rows?

我的代码:

import csv
import Write

paths = [
         'Finance.CSV',
         'Energy.CSV',
         'Basic Industries Companies.CSV',
         'Consumer Durables Companies.CSV',
         'Consumer Non-Durables Companies.CSV',
         'Consumer Services Companies.CSV',
         'Health Care Companies.CSV',
         'Public Utilities Companies.CSV',
         'Technology Companies.CSV',
         'Transportation Companies.CSV'
         ]

def collect():
    lst = []

    for path in paths:
        file=open( 'C:/Users/Rasmus/Desktop/Sectors/' + path, "r")
        reader = csv.reader(file)

        for line in reader:
            tmpLst = []
            tmpLst.append(line[0])
            tmpLst.append(line[7])
            lst.append(tmpLst)
            #print(line[0] + ", " + line[7])

    Write.UpdateCSV(lst)

collect()

import csv

class UpdateCSV():
    def __init__(self, lst):
        #print(lst)
        #resultFile = open("output.csv",'w')
        #wr = csv.writer(resultFile, dialect='excel')

        filewriter = csv.writer(open("output.csv", "wb"))

        filewriter.writerows(lst)


推荐答案

您的方法在Python 2中有效。

Your method works in Python 2.

但是在python 3中,您不能以二进制模式打开文本文件,否则write方法将需要字节。

But in python 3 you cannot open a text file in binary mode or the write method will expect bytes.

正确的处理方法在python 3中(添加了 with 语句,以确保退出 with 块时关闭文件):

A correct way of doing it in python 3 (with, added the with statement that ensures that the file is closed when exiting the with block):

with open("output.csv", "w", newline='') as f:
    filewriter = csv.writer(f)

(省略 newline 参数有效,但由于额外的回车,在Windows系统中插入了空白行,这可能是您所描述的问题)

(omitting the newline parameter works but inserts a "blank" line in windows systems because of extra carriage return, that's probably the problem you're describing)

编辑:我检查了csv模块文档,还有一种更好的方法,可与python 2 3配合使用,这将更改csv lineterminator

I checked csv module documentation, and there's an even better way to do this, works with python 2 and 3, which is to change csv lineterminator:

with open("output.csv","w") as f:
    filewriter = csv.writer(f,lineterminator="\n")

我之前问过一个问题,更新了我的答案以反映以下内容:便携式在python 2或python 3中编写csv文件的方式

I had asked a question some time ago and just updated my answer to reflect that: portable way to write csv file in python 2 or python 3

编辑2:2.7.12和3.5.2版的python不需要所有这些。似乎有人永久解决了该问题。但是并不是所有人都可以升级python的次要版本(由于公司政策,合格工具取决于给定版本...)

EDIT 2: 2.7.12 and 3.5.2 version of python don't need all this. Seems that someone fixed the problem for good. But not everyone can upgrade even the minor versions of python (because of company policies, qualified tools depending on a given version...)

这篇关于csv writer预期的类似字节和行之间的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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