1

Then genfromtxt method of numpy load an ndarray from a text file. However, if the text file is empty, the method would raised an IOError while I expected an empty ndarray:

IOError: End-of-file reached before encountering data.

Is there any solution to get an empty ndarray if the text file is emtpy?

Eastsun
  • 18,526
  • 6
  • 57
  • 81
  • 1
    Update your NumPy. The error has been changed into a warning: https://github.com/numpy/numpy/commit/72ab385d17d9067f97652aeae87a820f7de41298 – Janne Karila Jun 03 '13 at 05:56

1 Answers1

2

Try using a try block to return an empty array on error:

try:
    a = np.genfromtext("filename.txt")
except IOError:
    a = np.array([]) # Or np.empty or np.zeros...
SethMMorton
  • 45,752
  • 12
  • 65
  • 86
  • Yes, that's works. But is there exists some parameter of `genfromtxt` to make this behave? – Eastsun Jun 03 '13 at 05:42
  • I disagree that it is misbehaving. The function is supposed to return data, and if it cannot there must have been an error so it raises one. It is the functionality I would expect. But as you can see from it's [documentation page](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) there is no such option. (I admit they don't specify what happens when the file is empty). – SethMMorton Jun 03 '13 at 05:46