Home > database >  How to read a text file (each individual item on its own line) into a 2D list in Python
How to read a text file (each individual item on its own line) into a 2D list in Python

Time:11-03

Trying to read a text file into a 2D list in Python. "people2.txt" is single lines in sequence (each item on its own line)

fred
23
ann
27
bob
24

Code so far:

details_list=[]

people2=open("people2.txt","r")

for line in people2.readlines():
    details_list.append(line.split())

people2.close()

print(details_list)

What I'm getting is each element in its own list, when I need "pairs"? I'm getting

[["fred"],["23"],["ann"],["27"],["bob"],["24"]]

What I need is:

[["fred","23"],["ann","27"],["bob","24"]]

CodePudding user response:

Use:

with open("people.txt") as infile:
    res = []
    for name, value in zip(infile, infile):
        res.append([name.strip(), value.strip()])
print(res)

Output

[['fred', '23'], ['ann', '27'], ['bob', '24']]

The expression:

for name, value in zip(infile, infile):

allows you to iterate in chunks of two lines over the file, as a side note you should also use a context manager to read files.

CodePudding user response:

If you already have a flat list of strings (which you will have if you replace line.split() with line.strip()), you can take 2 slices of that list with step 2 (i.e. one slice has the even-indexed elements, the other has the odd-indexed elements), then use zip to pair them up:

lines = ["Fred", "23", "Ann", "27", "Bob", "24"]
pairs = list(zip(lines[::2], lines[1::2]))
print(pairs)

This outputs

[('Fred', '23'), ('Ann', '27'), ('Bob', '24')]

This works beyond just file reading, but if you have a large file, it would be more performant to just read them as pairs to begin with.

  • Related