Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas.read_csv FileNotFoundError: File b'\xe2\x80\xaa<etc>' despite correct path

I'm trying to load a .csv file using the pd.read_csv() function when I get an error despite the file path being correct and using raw strings.

import pandas as pd
df = pd.read_csv('‪C:\\Users\\user\\Desktop\\datafile.csv')
df = pd.read_csv(r'‪C:\Users\user\Desktop\datafile.csv')
df = pd.read_csv('C:/Users/user/Desktop/datafile.csv')

all gives the error below:

FileNotFoundError: File b'\xe2\x80\xaaC:/Users/user/Desktop/tutorial.csv' (or the relevant path) does not exist.

Only when i copy the file into the working directory will it load correct.

Is anyone aware of what might be causing the error?

I had previously loaded other datasets with full filepaths without any problems and I'm currently only encountering issues since I've re-installed my python (via Anaconda package installer).


Edit:
I've found the issue that was causing the problem.
When I was copying the filepath over from the file properties window, I unwittingly copied another character that seems invisible.
Assigning that copied string also gives an unicode error.

Deleting that invisible character made any of above code work.

like image 637
Impuls3H Avatar asked Feb 10 '17 17:02

Impuls3H


3 Answers

Try this and see if it works. This is independent of the path you provide.

pd.read_csv(r'C:\Users\aiLab\Desktop\example.csv')

Here r is a special character and means raw string. So prefix it to your string literal.

https://www.journaldev.com/23598/python-raw-string:

Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash () as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

like image 117
WaterRocket8236 Avatar answered Sep 22 '22 21:09

WaterRocket8236


$10 says your file path is correct with respect to the location of the .py file, but incorrect with respect to the location from which you call python

For example, let's say script.py is located in ~/script/, and file.csv is located in ~/. Let's say script.py contains

import pandas
df = pandas.read_csv('../file.csv') # correct path from ~/script/ where script.py resides

If from ~/ you run python script/script.py, you will get the FileNotFound error. However, if from ~/script/ you run python script.py, it will work.

like image 31
hertopnerd Avatar answered Sep 22 '22 21:09

hertopnerd


I know following is a silly mistake but it could be the problem with your file.

I've renamed the file manually from adfa123 to abc.csv. The extension of the file was hidden, after renaming, Actual File name became abc.csv.csv. I've then removed the extra .csv from the name and everything was fine.

Hope it could help anyone else.

like image 35
Waqar Khan Avatar answered Sep 23 '22 21:09

Waqar Khan