Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors when importing files into spyder (Correct directory)

Here is my code

import pandas as pd
all_ages = pd.read_csv("all-ages.csv")
all_ages.head(5)

And I have already put the csv file in the working directory, but I still encounter

OSError: File b'all-ages.csv' does not exist

But if I type each line in the Console instead of Script, it works sometimes.

like image 221
Zihua Wu Avatar asked Aug 21 '26 22:08

Zihua Wu


1 Answers

You'd better provide the absolute file path. Python uses the current working directory which depends on where you invoke/run your python script.

Even you put your python script and csv file "all-ages.csv" under the same directory, the current working directory might be different.

For example:

/folder1/folder2/myscript.py
/folder1/folder2/all-ages.csv

if you run python myscript.py under directory folder2, it can find all-ages.csv, but if you invoke python folder2/myscript.py under folder1, the current working directory is folder1, and it cannot find all-ages.csv

like image 158
Haifeng Zhang Avatar answered Aug 24 '26 12:08

Haifeng Zhang