-1

I have TXT file with float numbers.

I can not convert it to float array in python.

f = open('Vmat.txt', 'r')
DATA = f.read()
DATA = DATA.split("\n")
for i in range(0,len(DATA),1):
    DATA[i] = DATA[i].replace(",","")
    DATA[i] = float(DATA[i])

ValueError Traceback (most recent call last)

ipython-input-73-e205bb7634f9 in module

4 for i in range(0,len(DATA),1):

5 DATA[i] = DATA[i].replace(",","")

----> 6 DATA[i] = float(DATA[i])

ValueError: could not convert string to float: ''

3 Answers3

0

The error message states that you are trying to cast an empty string ('') to a float which is impossible. This is probably because you have an empty line at the end of your file.

Sacha L
  • 1
  • 1
0
f = open('Vmat.txt', 'r')
DATA = f.read()
DATA = DATA.split("\n")
for i in range(0,len(DATA),1):
    if not DATA[i]:
        continue
    DATA[i] = DATA[i].replace(",","")
    DATA[i] = float(DATA[i])

This might work if the program crashes at the end because of an empty line.

Why are you replacing a comma with nothing? How will it keep its float value and not turn into a integer? DATA[i] = DATA[i].replace(",","") might also help

0
f = open('Vmat.txt', 'r') 
DATA = f.read() 
DATA = DATA.split("\n") 
NEW_DATA = []
for i in DATA: 
   try: 
      if float(i): 
         NEW_DATA.append(float(i))  
   except ValueError: 
      print("Not float value")
print(NEW_DATA)
joanis
  • 10,635
  • 14
  • 30
  • 40