Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

making a list of lists from a file

I want to make a function that receives a file of several lines, for example:

A B 1
C D 2
E F 3

and returns a list of lists like this: [[‘A’, ‘B’, ‘1’], [‘C’, ‘D’, ‘2’], [‘E’, ‘F’, ‘3’]]

This is the code I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def f(filename: str) -> list:
    with open(filename,'r') as file:
        content=file.readlines()
        file.close()
        for i in range(len(content)):
            l=[list(content[i].split(" "))]
        return l

but when I call the file I get only: [[‘A’, ‘B’, ‘1’]]

How can I fix it please?

>Solution :

This is one way you could do it:

abc.txt:

A B 1
C D 2
E F 3

Code:

def f(filename: str) -> list:
    with open(filename,'r') as file:
        return([x.split() for x in file])

print(f("abc.txt"))

Result:

[['A', 'B', '1'], ['C', 'D', '2'], ['E', 'F', '3']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading