I am creating a graph in python using a text file for the source data and matplotlib to plot the graph.
The simple logic below works well.
But is there a way to get have numpy.gentfromtxt only read the first 50 lines from the file ‘temperature_logging’? Currently it reads the entire file.
temp = numpy.genfromtxt('temperature_logging',dtype=None,usecols=(0))
time = numpy.genfromtxt('temperature_logging',dtype=None,usecols=(1))
dates = matplotlib.dates.datestr2num(time)
pylab.plot_date(dates,temp,xdate=True,fmt='b-')
pylab.savefig('gp.png')
contents in temperature_logging;
21.75 12-01-2012-15:53:35
21.75 12-01-2012-15:54:35
21.75 12-01-2012-15:55:35
.
.
.
numpy.genfromtxtaccepts iterators as well as files. That means it will accept the output ofitertools.islice. Here,test.txtis a five-line file:One might think this would be slower than letting
numpyhandle the file IO, but a quick test suggests otherwise.genfromtxtprovides askip_footerkeyword argument that you can use if you know how long the file is……but a few informal tests on a 1000-line file suggest that using
isliceis faster even if you skip only a few lines: