0

I have a text file sample.txt(space delimited) in this format

12 john E 44 L
13 adam D 78 L
14 tue E 98 L

I want to to convert this file into a nested list

table_data = [
        [12, 'john', 'E', 44, 'L'],
        [13, 'adam', 'D', 78, 'L'],
        [14, 'tue', 'E', 98, 'L'],
]

How can i do it ?

3 Answers 3

5

Use str.split and a list comprehension:

with open('filename') as f:
   table_data = [ line.split() for line in f]

If you want the numbers to be converted to integers then write an additional function that processes each item on a give line:

def func(x):
    try:                                                         
        return int(x)
    except ValueError:
        return x
>>> with open('abc1') as f:
...     table_data = [[ func(x) for x in line.split()] for line in f]
...     
>>> table_data
[[12, 'john', 'E', 44, 'L'],
 [13, 'adam', 'D', 78, 'L'],
 [14, 'tue', 'E', 98, 'L']]
Sign up to request clarification or add additional context in comments.

2 Comments

map(func,line.split()) would be nicer
@HennyH Some people hate map, so I prefer a LC. :/
1

Use the inbuilt csv package

from csv import reader

types = [int, str, str, int, str]

with open('sample.txt', 'rb') as f:
    table_data = [[t(v) for v, t in zip(row, types)] for row in reader(f, delimiter=' ')]
print table_data

Has the output:

[[12, 'john', 'E', 44, 'L'], [13, 'adam', 'D', 78, 'L'], [14, 'tue', 'E', 98, 'L']]

Comments

0
a = '''12 john E 44 L
13 adam D 78 L
14 tue E 98 L'''

table_data = [b.split(' ') for b in a.split('\n')]
print table_data

Where table_data is:

table_data = [['12', 'john', 'E', '44', 'L'],
              ['13', 'adam', 'D', '78', 'L'],
              ['14', 'tue', 'E', '98', 'L']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.