sharath
sharath

Reputation: 55

how to write the contents of a file into lists in python?

i am learning python programming and am stuck with this problem.I looked into the other examples which reads the file input and makes the entire thing as a single list or as a string link to that example but i want each line to be a list(nested lists) how do i do it please help
The text file is a.txt

1234 456 789 10 11 12 13

4456 585 568 2 11 13 15 

the output of the code must be like this

[ [1234 456 789 10 11 12 13],[4456 585 568 2 11 13 15] ]

Upvotes: 3

Views: 153

Answers (4)

Adam Smith
Adam Smith

Reputation: 54163

No reason to do readlines -- just iterate over the file.

with open('path/to/file.txt') as f:
    result = [line.split() for line in f]

If you want a list of lists of ints:

with open('path/to/file.txt') as f:
    result = [map(int, line.split()) for line in f]
    # [list(map(int, line.split())) for line in f] in Python3

Upvotes: 5

Bhargav Rao
Bhargav Rao

Reputation: 52071

You can do

with open('a.txt') as f:
     [[i.strip()] for i in f.readlines()]

It will print

[['1234 456 789 10 11 12 13'], ['4456 585 568 2 11 13 15']]

Note - This is an answer to your initial problem to print strings

To print exactly as you want without quotes, this is a very bad approach

print(repr([[i.strip()] for i in f.readlines()]).replace("'",''))

which will print

[[1234 456 789 10 11 12 13], [4456 585 568 2 11 13 15]]

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16711

lines = open('file.txt').readlines() # parse file by lines
lines = [i.strip().split(' ') for i in lines] # remove newlines, split spaces
lines = [[int(i) for i in j] for j in lines] # cast to integers

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881555

Looks like you want integers, not strings, in the resulting lists; if so:

with open(filename) as f:
    result = [[int(x) for x in line.strip().split()] for line in f]

Upvotes: 2

Related Questions