Chris Parry Chris Parry - 4 months ago 165
Python Question

Reading text file with numpy.loadtxt

I am getting an error when trying to read a text file.

import numpy as np

fnam = 'file.txt'
test_fnames = np.loadtxt(fnam, dtype=None, delimiter=',')
test_fnames


I now get this error:

ValueError: could not convert string to float:


The file content is just a comma separated list of numbers. Perhaps there is a space at the end of the file that is causing an error?

1,2,3,4,5,6,7,7,8,9122,3,3,45,5,6


Thanks. The problem was the way I wrote the text file in Torch7.

Answer

You could use np.genfromtxt() instead of np.loadtxt. Because the first one let handles missing values :

import numpy as np

fnam = 'file.txt'
test_fnames = np.genfromtxt(fnam, dtype=None, delimiter=',')

You could also try :

import numpy as np

fnam = 'file.txt'
test_fnames = np.genfromtxt(fnam, dtype=None, delimiter=',')[:,:-1]

It's just an idea ^^ But if you want, upload your data file somewhere, give me the link and I will see ;)

Comments