error on loading files using numpy python

Viewed 44

i have many text files that contain integers present inside a directory /home/gkl/file/*.rtd.2_file_*.txt_*

i just want to load using numpy and i am getting error

import numpy as np
import glob
import os

files = [os.path.basename(x) for x in glob.glob("/home/gkl/file/*.rtd.2_file_*.txt_*")]
print(files)
inpdata=np.loadtxt(names)
print(inpdata)

i am getting error ValueError: could not convert string to float: 'mst.rtd.2_file_345.txt_1'

after that i tried

import numpy as np
import glob
import os

files = [os.path.basename(x) for x in glob.glob("/home/gkl/file/*.rtd.2_file_*.txt_*")]
print(files)
inpdata=np.loadtxt(float(names))
print(inpdata)

still i get error

inpdata=np.loadtxt(float(names))
TypeError: float() argument must be a string or a number, not 'list'

i need experts help here

1 Answers

The problem is that you have a list of file names, but np.loadtxt expects a single file or filename. So you essentially have to call loadtxt in a for-loop:

import numpy as np
import glob
import os

files = [os.path.basename(x) for x in glob.glob("/home/gkl/file/*.rtd.2_file_*.txt_*")]
print(files)
inpdata = [np.loadtxt(file) for file in files]
print(inpdata)

If this still does not work I'd need to see what is in the files to debug further.

Related