Python Forum
Importing a csv file with spyder - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Importing a csv file with spyder (/thread-10091.html)



Importing a csv file with spyder - Scott - May-12-2018

Hi Everyone I am trying to import a csv file called 'train' in Spyder and it is not working.

code:
train = pd.read_csv('C:\Users\SGrah\OneDrive\Documents\Python Scripts\Python for Data Analysis\train.csv')
train[:4]
I get this error below:

File "<ipython-input-13-93db4cee1b88>", line 1
train = pd.read_csv('C:\Users\SGrah\OneDrive\Documents\Python Scripts\Python for Data Analysis\train.csv')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

This is really holding me back any help is greatly appreciated. My text book does this code:
train = pd.read_csv('datasets/titanic/train.csv')
I don't really get how the path does not have a drive but anyhow can anyone please help?

The file is saved in this location on my computer: C:\Users\SGrah\OneDrive\Documents\Python Scripts\Python for Data Analysis\train.csv'.

Thanks a lot


RE: Importing a csv file with spyder - wavic - May-12-2018

The path from the book doesn't have a drive because is local to the script's location. datasets folder is in the same folder as the script is.

In Python, the backslash is used for the escape characters. For example the new line - '\n'. You can use / for the path as it is in web addresses even on Windows system. Try it.
Also, you can try to use a raw string for the path: r'C:\Users\SGrah\OneDrive\Documents\Python Scripts\Python for Data Analysis\train.csv'.

Check the path for mistypes.


RE: Importing a csv file with spyder - Scott - May-12-2018

The r trick worked, thank you so much.

So python for paths does not like \? I just right clicked and copy pasted the location which had \.


RE: Importing a csv file with spyder - wavic - May-12-2018

I am not saying that. Python will work with both \ and /. But it's safe to use / for paths because the \ is used in Python for escape characters. That is why r'' forks. The string is interpreted as it is. Another way is to use \\ for any \ in the path.