Python 为什么pandas read#u csv能够找到文件,而os.listdir不';T

Python 为什么pandas read#u csv能够找到文件,而os.listdir不';T,python,pandas,operating-system,Python,Pandas,Operating System,我在~/Google Drive/iNat/full.csv上有一个文件 iNatPATH = r"~/Google Drive/iNat/" FILENAME = iNatPATH + "full.csv" 我不明白熊猫为什么能够读取csv文件: 将熊猫作为pd导入 原始数据=pd.read\U csv(文件名) #没有返回错误。 但是os找不到它: 导入操作系统 os.path.exists(文件名) #输出错误 我在macOS系统中运行这段代码

我在
~/Google Drive/iNat/full.csv
上有一个文件

iNatPATH = r"~/Google Drive/iNat/"
FILENAME = iNatPATH + "full.csv"
我不明白熊猫为什么能够读取
csv
文件:

将熊猫作为pd导入
原始数据=pd.read\U csv(文件名)
#没有返回错误。
但是
os
找不到它:

导入操作系统
os.path.exists(文件名)
#输出错误
我在macOS系统中运行这段代码,在GoogleColab的本地运行时运行

我的工作目录是(因为我使用的是绝对路径,所以不应该相关):

>os.getcwd()
...
“/Users//Documents”

您的问题是
os.path.exists()
函数没有展开
~
字符。为了解决这个问题,相同的
os
模块提供了
os.path.expanduser(path)
函数,该函数将在路径中为您展开该用户变量

适用于您的情况:

iNatPATH=r“~/Google-Drive/iNat/”
FILENAME=iNatPATH+“full.csv”
#展开~字符
FILENAME=os.path.expanduser(文件名)
#最后,您可以使用exists()函数再次检查
os.path.exists(文件名)

参考资料:

我打赌
os.path.exists
不会扩展
~
字符。似乎您应该在path变量之前应用
os.path.expanduser(path)
。很好:)那么让我写一个适当的答案