0

I'm trying to read a CSV file that I have on my computer in a Jupyter Notebook. I using Pandas pd.read_csv(file path) but I'm getting this error:

File "C:\Users\pc\AppData\Local\Temp/ipykernel_15328/2333079912.py", line 1
flight_df=pd.read_csv('C:\Users\pc\Desktop\Work\flight.csv')
                                                           ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: 
truncated \UXXXXXXXX escape

Here is my code so far:

#Calling Libraries
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

flight_df=pd.read_csv('C:\Users\pc\Desktop\Work\flight.csv')
  • `flight_df=pd.read_csv(r'C:\Users\pc\Desktop\Work\flight.csv')` – Matt Apr 04 '22 at 14:41
  • TLDR: google your exact error to find an exact solution... top link for your error: https://stackoverflow.com/questions/37400974/unicode-error-unicodeescape-codec-cant-decode-bytes-in-position-2-3-trunca using backslash `\` in strings will cause problems because it is an escape character. You can use a raw string as above or see reasons here – Matt Apr 04 '22 at 14:43

3 Answers3

0

try C:/Users/pc/Desktop/Work/flight.csv or escape C:\\Users\\pc\\Desktop\\Work\\flight.csvotherwise \ is interpreted as escape sequence.

Dyno Fu
  • 8,753
  • 4
  • 39
  • 64
0

If you change the string to either contain double backslashes \\ as directory separators or put a r in front of it like

flight_df=pd.read_csv(r'C:\Users\pc\Desktop\Work\flight.csv')

the loading of the file should succeed.


As an addition, the error regards the escaping of characters like \U in C:\Users.

Erik Wessel
  • 501
  • 3
  • 8
0

Its because your path as treated as normal string. You can do this to fix your issue:

flight_df = pd.read_csv(r'C:\Users\pc\Desktop\Work\flight.csv')
SM1312
  • 516
  • 4
  • 13