Python genfromtxt file path

DavideL picture DavideL · Apr 30, 2015 · Viewed 9.7k times · Source

I have an extremely basic problem with the numpy.genfromtxt function. I'm using the Enthought Canopy package: where shall I save the file.txt I want to use, or how shall I tell Python where to look for it? When using IDLE I simply save the file in a preset folder such as C:\Users\Davide\Python\data.txt and what I get is

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

while working with Canopy the same code gives IOError: data.txt not found, nor something like np.genfromtxt('C:\Users\Davide\Python\data.txt') works. I'm sorry for the question's banality but I'm really going crazy with this. Thanks for help.

Answer

EdChum picture EdChum · Apr 30, 2015

You can pass a fully qualified path but this:

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

won't work because back slashes need to be escaped:

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

or you could use a raw string:

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

As to where the currect saved location is you can query this using os.getcwd():

In [269]:

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