-2

I am trying to work on a csv file in python

#code experiments
import csv
from statistics import mean
with open("C:\Users\xyr\zzz\kkkk\mmmm\ooooo\mpg.csv",'r') as csvfile:
    reader=list(csv.DictReader(csvfile))
    for item in reader:
        print (item)
        l=[item['cty']]
        new_list=list(map(float,l))
        res=(mean(new_list))
        print (res)

gives me the error

unicodeescape' codec can't decode bytes in position

However, if I am opening same file in an environment of anaconda's jupyter notebook I am able to open the file. This error is coming when I am using python IDLE environment what could be the reason for this error, how can I get rid of these in IDLE environment? I have tried using single quotes instead of double quotes but still the error remains.

Terry Jan Reedy
  • 15,989
  • 1
  • 33
  • 48
ss321c
  • 551
  • 1
  • 6
  • 18
  • try specifying the `encoding='utf-8'` – Axois Aug 11 '19 at 07:58
  • how do I specify the encoding I am trying to import an excel sheet. In which line should I specify that I tried putting it before with statement but it gave error. – ss321c Aug 11 '19 at 08:26
  • with open("C:\Users\xyr\zzz\kkkk\mmmm\ooooo\mpg.csv",'r' , encoding = 'utf-8') – Axois Aug 11 '19 at 08:33
  • ok I did so this gives same error – ss321c Aug 11 '19 at 08:35
  • I think stanislav has fixed your issue. All you need to do is to add an additional \ to your url, for example `C:\\Users\\xyr\\zzz\\kkkk\\mmmm\\ooooo\\mpg.csv` I am assuming you are using python3 in this. The difference is that in python3, strings are regarded as unicode – Axois Aug 11 '19 at 08:42
  • 1
    Possible duplicate of [Windows path in Python](https://stackoverflow.com/questions/2953834/windows-path-in-python) – mkrieger1 Aug 11 '19 at 09:14
  • The error message is from Python, not IDLE. You would see the same if you ran the same code in directly in python, without IDLE. This is a common newbie problem, so jupyter must be recognizing this as a Windows path and doing something to your code before running it, or using an altered python.exe. – Terry Jan Reedy Aug 12 '19 at 07:56

1 Answers1

0

The main reason you get an error is that \u is an Unicode escape symbol. if symbols after that are not numeric - it raises an exception

Thy adding extra slashes in your path:

C:\\Users\\xxx\\...

or just use r prefix:

r'C:\Users...'