-1

I have a txt file, which looks like that:


Description
Description
0 0 170. 170. 40.02 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 18.09228
1 0 170. 170. 70.80 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 12.09736
....
1 0 170. 170. 06.48 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 12.09736


I have tried to do this using:

data = np.loadtxt('Filename.txt', comments='#', delimiter=' ', skiprows=2)

But I get the error massage "could not convert string to float:" Probably it can occur because in the data there are different number of spaces between the columns.

Also I tried:

with open('Filename.txt') as f:  
   data = f.readlines()[2:] 

But then I dont know how to split it into columns. I just need an array with numbers after 'description' to make some computations. I would really appreciate if someone could suggest a solution.

Yuliya
  • 1
  • 1
  • Could you describe how the output should look like? – sandertjuh May 14 '21 at 14:13
  • `[line.split(" ") for line in data]` would this bring you closer to what you need. – samusa May 14 '21 at 14:17
  • I would bet that the issue is with the string (170.) this is not a number so np.load txt probably fails here. Samusa posted would split your text into columns but you need to also manually fix all the numbers that dont end in a digit. i.e 170. -> 170.0 – Jason Chia May 14 '21 at 14:29
  • What is the expected output/behaviour? – AMC May 14 '21 at 20:18
  • I just want an array, which consist of these numbers to work with. – Yuliya May 15 '21 at 10:58

1 Answers1

0

If the file has values separated by a space you could do something like:

contents=[]
with open('Filename.txt') as f:
   for line in f.readlines():
     contents.append(line.rstrip().split(' '))

For skipping the first 2 columns:

contents=[]
with open('Filename.txt') as f:
  for line in f.readlines():
    line=line.rstrip().split(' ')
    if len(line)<2:
      continue
    contents.append(line[2:])
Chase LP
  • 229
  • 2
  • 7