Home > Software design >  Reading a text file (tab/space delimited) having named columns into lists with the lists having the
Reading a text file (tab/space delimited) having named columns into lists with the lists having the

Time:01-14

My text file looks like this:

x   y   z   D
0   0   350 10
50  -50 400 15
100 50  450 10
-25 100 500 10  

where the columns are tab-separated. I want to import it into 4 Python lists having the name of the columns:

x = [0, 50, 100, -25]
y = [0, -50, 50, 100]
z = [350, 400, 450, 500]
D = [10, 15, 10, 10]

Is it possible to do such using some in-built functions without resorting to importing Pandas or some special packages?

CodePudding user response:

I suggest this approach...

Construct a dictionary keyed on the column names (x, y, z, D)

Each key has a value which is a list.

Consume the file appending the individual values to the appropriate keys.

from collections import defaultdict
with open('t.txt') as infile:
    cols = next(infile).strip().split()
    d = defaultdict(list)
    for line in infile:
        for i, t in enumerate(line.strip().split()):
            d[cols[i]].append(int(t))
    for k, v in d.items():
        print(f'{k} = {v}')

Output:

x = [0, 50, 100, -25]
y = [0, -50, 50, 100]
z = [350, 400, 450, 500]
D = [10, 15, 10, 10]

CodePudding user response:

you could do this:

import re
with open('file.txt') as f:
    data = [re.split('[ ] |\t',x) for x in f.read().split('\n')]
res = dict((x,[]) for x in data[0])
for i in data[1:]:
    for j in range(len(i)):
        res[data[0][j]].append(i[j])
print(res)
  •  Tags:  
  • Related