简体   繁体   中英

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] ]

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

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]]
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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM