[Python] 使用 ~/ 開頭的path 會顯示檔案不存在

Posted in :

範例:

f_path = '~/Documents/test.csv'
os.path.isfile(f_path)
False

解法:

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 REALLY want to use ~ as home, you can do

from os.path import expanduser
home = expanduser("~")

也可以這樣子用:

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))

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *