Home > Software design >  making a list of lists from a file
making a list of lists from a file

Time:04-01

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:

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?

CodePudding user response:

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

CodePudding user response:

Try this

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

  • Related