0

I am having this little problem with decoding nested list from csv file. I can't write to csv because of unicode error so I have to encode it but when I want to decode it I get this error: attributeerror: 'str' object has no attribute 'decode' I get that somewhere it becomes a string, so even if I have to change the way of writing to the csv file it's ok. Also, I think it reads incorrectly because it reads one line in csv file like two different lists. Here is the code for decoding:

import csv
f = open('C:\\Users\\igori\\PycharmProjects\\test\\stizanje_robe.csv')
csv_ = csv.reader(f, delimiter=' ')
for row in reversed(list(csv_)):
    if len(row) != 0:
        for i in row:
            print(i)
            i.decode('utf-8')
            print(i)

Here is the code for encoding and writing:

    kada = '20.8.2021.'
    sta = 'neće raditi'
    koliko = 50
    csv_file = open('C:\\Users\\igori\\PycharmProjects\\test\\stizanje_robe.csv', 'a')
    csvWriter = csv.writer(csv_file)
    csvWriter.writerow([kada, sta.encode("utf-8"), koliko])

Here I added those 'kada' 'sta' and 'koliko' variables but I get that from inputs. and here is how csv file looks like:

20.2.2021.,b'ZEOMIN 5L',20

1.3.2021.,b'FITOCAL 5L',30

1.3.2021.,b'FITOTRIJAK 5L',20

20.4.2021.,b'ZEOBIN 5L',40

5.7.2021.,b'FITOMIL 5L',25

20.8.2021.,b'NE\xc4\x86E RADITI',50

If you need some more info that I forgot to give, please tell me. Thank you!

ixzor
  • 57
  • 6
  • 1
    That's not valid CSV. Whoever wrote that file has no idea. –  Jan 15 '21 at 01:37
  • 1
    Is that really what the `.csv` looks like? I have a suspicion that you are showing us something that your code has read from the file and printed. Open it in Notepad (or better, Notepad++) and post whatever it says is in the file. – BoarGules Jan 15 '21 at 02:13
  • "I can't write to csv because of unicode error" -> see [this answer](https://stackoverflow.com/a/54967498/5320906) for how to handle this. Your solution of calling `sta.encode('utf-8')` is what is corrupting the file. – snakecharmerb Jan 15 '21 at 09:05
  • @snakecharmerb thank you. Works great now. Plus you helped me trim down couple of lines of code. – ixzor Jan 15 '21 at 14:09

0 Answers0