M
M
mr_drinkens892018-01-26 23:56:54
Python
mr_drinkens89, 2018-01-26 23:56:54

Python3 and CSV write to cp1251?

Good day.
Python3.6
Faced a problem with writing csv strings in cp1251 encoding.

def create_item_order_info(self):
        from io import StringIO
        file = StringIO()
        writer = csv.writer(file,delimiter=';')

        fields = ['Но. чека',
                          'Но. заказа',
                          'Но. позиции',
                          'Но. Карты лояльности',
                          'Цена',
                          'Количество',
                          'Сумма',
                          'Стоимость доставки',
                          'Итог',
                          'Дата заказа',
                          'Дата доставки',
                          'Статус',
                          'Комисс. товар',
                          'Накладная Но']

        writer.writerow([field for field in fields])

        for item in self.queryset:
            writer.writerow( ['',
                              int( item.order.order_number ),
                              int( item.product.vendor_id ),
                              '',
                              int( item.product.stock_price ),
                              int( item.product_amount ),
                              int( item.product.stock_price * item.product_amount ),
                              '0',
                              int( item.product.stock_price * item.product_amount ),
                              item.order.created.date().strftime( '%d.%m.%Y' ),
                              item.order.created.date().strftime( '%d.%m.%Y' ),
                              'Возврат',
                              'Да',
                              ''] )


        response = HttpResponse(file.getvalue(), content_type='text/csv' )

        response['Content-Disposition'] = 'attachment; filename="return_info.csv"'

        return response

At the output I get csv in utf8.
How can I get this file in cp1251 encoding?
(the system where the file is transferred requires exactly cp1251)
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2018-01-27
@mr_drinkens89

Enough to just add.encode('cp1251')
file.getvalue().encode('cp1251')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question