Search code examples
pythonnumpygenfromtxt

numpy#genfromtxt raise an IOError while the txt file is empty


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?


Solution

  • 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...