-1

Can anyone tell me why this code is not working?

import pandas as pd
​
df = pd.read_csv('C:\Users\M-Sohrab\Desktop\project\trips.csv')
​
print(df.to_string())
​

I am going to read a csv file in Python but the error

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

shows up!

import pandas as pd ​ df = pd.read_csv('C:\Users\M-Sohrab\Desktop\project\trips.csv') ​ print(df.to_string())

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • What's the actual *full* error? The path isn't escaped so `\Users` will be treated as an escape sequence. Use a raw literal (r'c:\User\...') instead. – Panagiotis Kanavos Aug 29 '23 at 08:48
  • Please format the second code snipped and tell us what's its purpose. Moreover, can you give us some hint on the actual file content? E.g. `cat trips.csv`, a screenshot, whatever – Patrizio Bertoni Aug 29 '23 at 08:49

1 Answers1

2

Try it like this:

import pandas as pd
​
df = pd.read_csv(r'C:\Users\M-Sohrab\Desktop\project\trips.csv')
​
print(df.to_string())

I just added an 'r' in front of your string.

See this question for more info

rootdoot
  • 323
  • 1
  • 2
  • 7