0

I have a model: (Python 3.5)

class Model(models.Model):
  import_file = models.FileField(upload_to="import")

  def save(self, *args, **kwargs):
    super(Model, self).save(*args, **kwargs)
    with open(self.import_file.name) as csvfile:
      reader = DictReader(csvfile, dialect='excel')
      for line in reader:
         print (line)

I got

'utf-8' codec can't decode byte 0x95 in position 15: invalid start byte
The string that could not be encoded/decoded was: !f�}

I tried with utf16, but then I got error with BOM.

Do you guys have any ideas?

EDIT1 I've just tried

...
with open(self.import_file.name, encoding='utf-8') as csvfile:     
...

Still same error:

'utf-8' codec can't decode byte 0x95 in position 15: invalid start byte

EDIT2

If I changed encoding to ISO-8859-1 I got:

line contains NULL byte
mrsolupo
  • 181
  • 10
  • Try `open(self.import_file.name, encoding='utf-8')` – Sergey Gornostaev Aug 22 '16 at 11:53
  • I've tried, pleas see an edit1 – mrsolupo Aug 22 '16 at 12:01
  • I have same problem with opening csv. In my case, the problem was solved by this code `reader = csv.DictReader(self.utf_8_encoder(cd['csv'].file.read().splitlines()), fieldnames=CountPointImport.get_import_fields())` where utf_8_encoder is a function: `def utf_8_encoder(self, unicode_csv_data): for line in unicode_csv_data: yield line.decode('ascii', 'ignore')` – Anna Aug 22 '16 at 12:14
  • Try changing the encoding. Something similar happened to me and it only worked with this encoding - `ISO-8859-1`. – xyres Aug 22 '16 at 12:22
  • Possible duplicate of [Python 3 CSV file giving UnicodeDecodeError: 'utf-8' codec can't decode byte error when I print](http://stackoverflow.com/questions/21504319/python-3-csv-file-giving-unicodedecodeerror-utf-8-codec-cant-decode-byte-err) – solarissmoke Aug 24 '16 at 04:57

0 Answers0