Python genfromtxt 文件路径

Python genfromtxt file path

我对 numpy.genfromtxt 函数有一个非常基本的问题。我正在使用 Enthought Canopy 包:我应该在哪里保存我想使用的 file.txt,或者我应该如何告诉 Python 在哪里寻找它?使用 IDLE 时,我只需将文件保存在预设文件夹中,例如 C:\Users\Davide\Python\data.txt,我得到的是

>>> import numpy as np
>>> np.genfromtxt('data.txt')
array([[ 33.1 ,  32.6 ,  18.2 ,  17.9 ],
       [ 32.95,  32.7 ,  17.95,  17.9 ],
       [ 32.9 ,  32.6 ,  18.  ,  17.9 ],
       [ 33.  ,  32.65,  18.  ,  17.9 ],
       [ 32.95,  32.65,  18.05,  17.9 ],
       [ 33.  ,  32.6 ,  18.  ,  17.9 ],
       [ 33.05,  32.7 ,  18.  ,  17.9 ],
       [ 33.05,  32.5 ,  18.1 ,  17.9 ],
       [ 33.  ,  32.6 ,  18.05,  17.9 ],
       [ 33.  ,  32.55,  18.  ,  17.95]])

在使用 Canopy 时,相同的代码给出了 IOError: data.txt not found,而 np.genfromtxt('C:\Users\Davide\Python\data.txt') 之类的代码也不起作用。对于这个问题的平庸,我深表歉意,但我真的为此发疯了。感谢帮助。

您可以传递完全限定的路径,但是:

np.genfromtxt('C:\Users\Davide\Python\data.txt') 

将无法工作,因为需要转义反斜杠:

np.genfromtxt('C:\Users\Davide\Python\data.txt') 

或者您可以使用原始字符串:

np.genfromtxt(r'C:\Users\Davide\Python\data.txt') 

关于当前保存的位置,您可以使用os.getcwd()查询:

In [269]:

import os
os.getcwd()
Out[269]:
'C:\WinPython-64bit-3.4.3.1\notebooks\docs'