3

我对 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')。我很抱歉这个问题很平庸,但我真的为此发疯了。感谢帮助。

4

1 回答 1

7

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

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'
于 2015-04-30T08:52:41.443 回答