Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
read_csv error
#1
here is my statement, and the error, the directory is correct, can you explian the issue? thanks

import pandas as pd

file = "C:\Users\MTS\Downloads\SPY.csv"
spy = pd.read_csv(file)
spy.head()
Quote:C:\Users\MTS\PycharmProjects\UnitTesting_Lynda\venv\Scripts\python.exe C:/Users/MTS/.PyCharmCE2019.1/config/scratches/scratch.py
File "C:/Users/MTS/.PyCharmCE2019.1/config/scratches/scratch.py", line 2
file = "C:\Users\MTS\Downloads\SPY.csv"
.........^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Process finished with exit code 1
Reply
#2
Single backslash gives the following character (or characters) a special meaning:
https://docs.python.org/2.0/ref/strings.html
https://docs.python.org/3/reference/lexi...s-literals

For example '\U' allows you to enter hexadecimal value that will get interpretted as unicode character, like this:
print('\U00000041')
Output:
A
So when you wrote C:\Users it expected 8 digits following 'U'.

You could try:
file_name = "C:\\Users\\MTS\\Downloads\\SPY.csv"
# or
file_name = "C:/Users/MTS/Downloads/SPY.csv"
Reply
#3
thanks i ended up adding the r prefix to the string and made it a "raw string" it worked

filename = r"C:\Users\MTS\Downloads\SPY.csv"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] dataframe and read_csv ju21878436312 4 2,826 Jun-16-2021, 06:01 AM
Last Post: ju21878436312
  Pandas Dataframe through read_csv() ift38375 1 2,172 May-29-2019, 05:56 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020