Skip to content Skip to sidebar Skip to footer

Read File As List Of Tuples

I want to read a file using python the result must be like (a list of tuples): myList=[(1, 'assignment_1', 85,100', '0.05'), ('2', 'assignment_2', '80', '100', '0.05'),

Solution 1:

You can convert the elements into the proper type immediately after the line they're in has been read:

from pprint import pprint

types = int, str, int, int, float
filename = 'assignments.txt'withopen(filename, "r") as inputfile:
    myList = []
    for line in inputfile:
        elements = tuple(t(e) for t,e inzip(types, line.split()))
        myList.append(elements)

pprint(myList)

Output:

[(1, 'assignment_1', 85, 100, 0.05),
 (2, 'assignment_2', 80, 100, 0.05),
 (3, 'assignment_3', 95, 100, 0.05)]

This could be done even more succinctly using a list comprehension:

withopen(filename, "r") as inputfile:
    myList = [tuple(t(e) for t,e inzip(types, line.split()))
                for line in inputfile]

Also note you don't need to use readlines() to read all the lines of a file into memory at once because files are iterable, line-by-line. This is described in the Tutorial in Python's online documentation.

Solution 2:

Adding to wpercy's answer, I would imagine the simplest way to achieve this would be the following.

withopen(filename, 'r') as input_file:
    my_list = [tuple(line.split()) for line in input_file]

Solution 3:

You can use something like:

myList = []
withopen("text_to_tuple.txt") as f:
    for line in f:
        myList.append(tuple(line.rstrip().split())) # rstrip() removes line breaks
print(myList)    
# [('1', 'assignment_1', '85', '100', '0.05'), ('2', 'assignment_2', '80', '100', '0.05'), ('3', 'assignment_3', '95', '100', '0.05')]

Post a Comment for "Read File As List Of Tuples"