Python 3.3 CSV.Writer 写入额外的空白行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16271236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:10:42  来源:igfitidea点击:

Python 3.3 CSV.Writer writes extra blank rows

pythoncsvpython-3.x

提问by Nyxynyx

Using Python 3.3 on Windows 8, when writing to a CSV file, I get the error TypeError: 'str' does not support the buffer interfaceand "wb"flag was used. However when only the "w"flag was used, I get no errors, but every row is separated by a blank row!

在 Windows 8 上使用 Python 3.3,写入 CSV 文件时,出现错误TypeError: 'str' does not support the buffer interface并使用了"wb"标志。然而,当只使用"w"标志时,我没有得到任何错误,但每一行都被一个空行分隔!

Problem Writing

问题写作

Code

代码

test_file_object = csv.reader( open("./files/test.csv", 'r') )
next(test_file_object )

with open("./files/forest.csv", 'wb') as myfile:
    open_file_object = csv.writer( open("./files/forest.csv", 'wb') )
    i = 0
    for row in test_file_object:
        row.insert(0, output[i].astype(np.uint8))
        open_file_object.writerow(row)
        i += 1

Error

错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-121-8cbb94f602a8> in <module>()
      8     for row in test_file_object:
      9         row.insert(0, output[i].astype(np.uint8))
---> 10         open_file_object.writerow(row)
     11         i += 1

TypeError: 'str' does not support the buffer interface


Problem Reading

问题阅读

When reading, I cant seem to use the "rb"flags so it will give the error iterator should return strings, not byteswhen trying to ignore the first row (headers).

阅读时,我似乎无法使用"rb"标志,因此iterator should return strings, not bytes在尝试忽略第一行(标题)时会出现错误。

Code

代码

csv_file_object = csv.reader(open('files/train.csv', 'rb'))
header = next(csv_file_object)
train_data = []
for row in csv_file_object:
    train_data.append(row)
train_data = np.array(train_data)

Error

错误

Error                                     Traceback (most recent call last)
<ipython-input-10-8b13d1956432> in <module>()
      1 csv_file_object = csv.reader(open('files/train.csv', 'rb'))
----> 2 header = next(csv_file_object)
      3 train_data = []
      4 for row in csv_file_object:
      5     train_data.append(row)

Error: iterator should return strings, not bytes (did you open the file in text mode?)

回答by AdriVelaz

Hi this may help you.

你好这可能对你有帮助。

First Problem,

第一个问题,

change

改变

with open("./files/forest.csv", 'wb') as myfile:
    open_file_object = csv.writer( open("./files/forest.csv", 'wb') )

to

with open("./files/forest.csv", 'w+') as myfile:
    open_file_object = csv.writer( open("./files/forest.csv", 'w+') )

Second problem:

第二个问题:

Same exact thing, except change to r+

完全相同,除了更改为 r+

If that doesn't work, you can always just use this to strip out all the blank rows after it's created.

如果这不起作用,您可以随时使用它在创建后删除所有空白行。

for row in csv:
    if row or any(row) or any(field.strip() for field in row):
        myfile.writerow(row)

Also, a little lesson. "rb" stands for reading bytes, essentially think of it as reading an integer only. I'm not to sure what's the content of your csv; however, there must be strings in that csv.

另外,一点教训。“rb”代表读取字节,本质上将其视为仅读取整数。我不确定你的 csv 的内容是什么;但是,该 csv 中必须有字符串。

This will help for future reference.

这将有助于将来参考。

The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):

参数 mode 指向以以下序列之一开头的字符串(其他字符可能跟在这些序列之后。):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

回答by pepr

The 'wb'mode was OK for Python 2. However, it is wrong in Python 3. In Python 3, the csv reader needs strings, not bytes. This way, you have to open it in text mode. However, the \nmust not be interpreted when reading the content. This way, you have to pass newline=''when opening the file:

'wb'模式在 Python 2 中是可以的。但是,在 Python 3 中是错误的。在 Python 3 中,csv 读取器需要字符串,而不是字节。这样,您必须以文本模式打开它。但是,\n阅读内容时不得解释。这样,你newline=''在打开文件的时候就必须通过:

with open("./files/forest.csv", newline='') as input_file \
     open('something_else.csv', 'w', newline='') as output_file:
    writer = csv.writer(output_file)
    ...

If the file is not pure ASCII, you should also consider to add the encoding=...parameter.

如果文件不是纯ASCII,还应该考虑添加encoding=...参数。