Given error even when text in file: UserWarning: loadtxt: Empty input file: "Stock.txt"


When I load a file using numpy.loadtxt, I get this funny warning:

UserWarning: genfromtxt: Empty input file: "stocks.text"

Here is a minimal example showing the problem:

import numpy as np
fl = open('stocks.txt', 'w')
fl.write("GME : 1\nSPY : 2\nBBBY : 3\n")
file_contents = np.genfromtxt('stocks.txt', delimiter=':')

Please can someone help with this error? I’m trying to build graphs by taking values out of the txt file


EDIT after additional info provided: The file is still opened for writing while you are trying to read from it via numpy. You must first close it by f.close().

The error shouldn’t be that the file is empty but more like "could not convert string to float". However, you are loading strings a trying to store them as floats. Specify dtype=str as argument of np.loadtxt function if you want to load strings. However, numpy arrays cannot store different types of variables in one array so you probably want to load the columns separately by specifying the usecols argument.

names = np.loadtxt(fname='Stock.txt', dtype=str, delimiter=' : ', usecols=0)
values = np.loadtxt(fname='Stock.txt', dtype=int, delimiter=' : ', usecols=1)

Answered By – gagi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published