Download text data file

I have a text file in the format below

id x, y
0[0.0, 1.0]
1[0.0, 2.0]
2[0.1, 2.5]
:
:

I need to download this text file. I tried:

numpy.genfromtxt('FileName', delimiter=",", names=True)

but existence [prevents reading the file. What can I do?

+4
source share
2 answers

You need to convert the file to the format that NumPy expects before submitting it to genfromtxt(). Fortunately, you can do this in Python itself.

f1 = open("file.txt", "rU")
f2 = open("output.txt", "wt")
for line in f1:
    line = line.replace("[", ",")
    line = line.replace("]", "")
    f2.write(line)
f2.close()
f1.close()

Hope this helps.

+3
source

'try it

import numpy as np
X=[] # keep x, y
id=[] # keep ids
file_toload=open('FileName',"r") # start reading a file
file_toload.readline()# get rid of headers
for line in file_toload: # loop through all remaining lines
   line =line.replace("[",",") # replace [ with comma first row becomes '0,0.0, 1.0]'
   line =line.replace("]","") # replace ] with empty string first row becomes '0,0.0, 1.0'
   line =line.replace(" ","") # replace white space with empty string  first row becomes '0,0.0,1.0' 
   line =line.replace("\n","") # replace break line with empty string , just in case there is one
   line =line.replace("\r","") # replace car. return with empty string , just in case there is one
   splits= line.split(",") # split by comma first row becomes ['0','0.0','1.0'] 
   id.append(float(splits[0])) # append id , contains [0.0] , you could use int() instead of float()   
   X.append([float(splits[1]),float(splits[2])]) # append x,y , [[0.0,1.0]]
file_toload.close() # close the file
X=np.array(X) # convert X to numpy
id=np.array(id) # convert id to numpy  
##### print shapes of the arrays #####
print (X.shape)
print (id.shape)
+1
source

All Articles