0

I have a text file full of data that I need to split into 8 arrays

this data looks like this: columns are are separated by spaces and each row is separated by a new line

201901010000 001 2458484.50001 300.0  0.0 -90.0    0.8 6.519E-12
201901010000 001 2458484.50001 300.0  0.0 -80.0    0.8 5.959E-12

I want 8 different array filled with the data from each column. so the first array would look like [201901010000, 201901010000, etc]. I've tried using split but it either creates a new array for every value or every row.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Kaiyaren
  • 7
  • 3
  • 1
    Please post your code. If you have every row, then you just need to `zip()` them to get every column. – wjandrea Aug 05 '21 at 20:53

2 Answers2

0

Here's the code (Note : this took quite a long time ):

with open('CHANGE THIS TO THE NAME OF YOUR TXT FILE DIRECTORY') as f:
    lines = f.readlines()

data = []

for i in range(len(lines[0].split(' '))):
    data.append([])


for j in range(len(lines[0].split(' '))):
    for i in range(len(str(lines).split("\n"))+1):
        if lines[i].split(' ')[j] != '':
            data[j].append((lines[i].split(' ')[j]))


# print data to see if it's correct
print(data)
0

This'll create a list data with 8 elements, each element is a list of the columns from your file.

data = [[] for _ in range(8)]
with open("/path/to/your/file.txt") as f:
    for line in f.readlines():
        elements = line.split()
        for x in range(8):
            data[x].append(elements[x])
print(data)

Result based on your example:

[['201901010000', '201901010000'], ['001', '001'], ['2458484.50001', '2458484.50001'], ['300.0', '300.0'], ['0.0', '0.0'], ['-90.0', '-80.0'], ['0.8', '0.8'], ['6.519E-12', '5.959E-12']]
alfinkel24
  • 551
  • 5
  • 13
  • this worked thank you! I will most likely separate each element of the array into separate arrays tho – Kaiyaren Aug 06 '21 at 16:24