2

I have a file 7.csv in directory: '~/Documents/Jane/analyst/test/1/'. I was able to read this file using pandas.read_csv function with no problem.

f_path = '~/Documents/Jane/analyst/test/1/7.csv'

pd.read_csv(f_path, index_col=None, header=0)

But when checking whether this file is exsiting using os.path.isfile(), the result return False.

os.path.isfile(f_path)

False

What could be the the possible error source?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
enaJ
  • 1,565
  • 5
  • 16
  • 29

2 Answers2

6

Both os.path.isfile() and os.path.exists() do not recognize ~ as the home directory. ~ is a shell variable not recognized in python. It has to be either fully specified or you can use relative directory name.

But if you want to use ~ as home, you can do

from os.path import expanduser
home = expanduser("~")
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Hun
  • 3,707
  • 2
  • 15
  • 15
1

As hun mentioned, your code should be

import os

f_path = '~/Documents/Jane/analyst/test/1/7.csv'
os.path.isfile(os.path.expanduser(f_path))

This will expand the tilde into an absolute path. ~, . and .. do not have the same meaning to the python os package that they do in a unix shell and need to be interpreted by separate functions.

sakurashinken
  • 3,940
  • 8
  • 34
  • 67