Подтвердить что ты не робот

Python 3.3 CSV.Writer пишет дополнительные пустые строки

Используя Python 3.3 в Windows 8, при записи в файл 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

Ошибка

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

Чтение проблем

При чтении я не могу использовать флаги "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)

Ошибка

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?)
4b9b3361

Ответ 1

Режим '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)
    ...

Если файл не является чистым ASCII, вы также должны рассмотреть возможность добавления параметра encoding=....

Ответ 2

Привет, это может вам помочь.

Первая проблема,

изменить

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

Вторая проблема:

То же самое, кроме изменения на r +

Если это не сработает, вы всегда можете просто использовать это, чтобы вырезать все пустые строки после его создания.

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

Кроме того, небольшой урок. "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.