Skip to content Skip to sidebar Skip to footer

Python: Read From File Into List

I want my program to read from a .txt file, which has data in its lines arranged like this: NUM NUM NAME NAME NAME. How could I read its lines into a list so that each line becomes

Solution 1:

Use str.split() without an argument to have whitespace collapsed and removed for you automatically, then apply int() to the first two elements:

withopen("info.txt", "r") as read:
    lines = []
    for item in read:
        row= item.split()
        row[:2] = map(int, row[:2])
        lines.append(row)

Note what here we loop directly over the file object, no need to read all lines into memory first.

Solution 2:

with open(file) as f:
    text = [map(int, l.split()[:2]) + l.split()[2:] for l in f]

Post a Comment for "Python: Read From File Into List"