Search code examples
pythonfilepath

An existing file not being identified using os.path.isfile function


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?


Solution

  • 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("~")