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

Nyx*_*nyx 19 python csv python-3.x

在Windows 8上使用Python 3.3,当写入CSV文件时,我收到错误TypeError: 'str' does not support the buffer interface并使用了"wb"标志.但是当只使用"w"标志时,我没有错误,但是每一行都被一个空行隔开!

问题写作

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
Run Code Online (Sandbox Code Playgroud)

错误

---------------------------------------------------------------------------
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
Run Code Online (Sandbox Code Playgroud)

问题阅读

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

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)
Run Code Online (Sandbox Code Playgroud)

错误

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?)
Run Code Online (Sandbox Code Playgroud)

pep*_*epr 25

'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)
    ...
Run Code Online (Sandbox Code Playgroud)

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

  • 从头开始创建CSV文件时,我需要做的就是`open('filename.csv','w',newline ='')`.谢谢! (3认同)
  • 谢谢你在Python 3中遇到了这个问题.从另一个项目http://stackoverflow.com/questions/8746908/why-does-csv-file-contain-a-blank-line-in-between-each-data-当输出行时,他们还建议使用Lineterminator ='\n'参数和csv模块的各种编写器函数.哪种方法更好?我认为使用内置open()函数的newline选项可能更pythonic,而不是通过导入的csv控制此行为? (2认同)

Adr*_*laz 3

你好,这可能对你有帮助。

第一个问题,

改变

with open("./files/forest.csv", 'wb') as myfile:
    open_file_object = csv.writer( open("./files/forest.csv", 'wb') )
Run Code Online (Sandbox Code Playgroud)

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

第二个问题:

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

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

for row in csv:
    if row or any(row) or any(field.strip() for field in row):
        myfile.writerow(row)
Run Code Online (Sandbox Code Playgroud)

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

这将有助于将来的参考。

参数模式指向以以下序列之一开头的字符串(这些序列后面可能有其他字符。):

 ``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.
Run Code Online (Sandbox Code Playgroud)