broncosaurus
broncosaurus

Reputation: 25

Reading multiple lines from another file into a tuple

I can't seem to pull each individual line from a .txt file into a tuple. The 'city-data.txt' file is just a list of the 50 states, capitols, and their lat/longs. I need to create a tuple of all the states.

This is my code so far -

def read_cities(file_name):
    file_name = open('city-data.txt' , 'r')
    for line in file_name:
        road_map = ((line.split('\t')))
        return road_map
    file_name.close()

print(read_cities('city-data.txt'))

When it's run, it only prints the very first line from the .txt file, as such:

['Alabama', 'Montgomery', '32.361538', '-86.279118\n']

Upvotes: 1

Views: 1177

Answers (1)

algrebe
algrebe

Reputation: 1651

The reason it prints only the very first line is because of this

for line in file_name:
    road_map = ((line.split('\t')))
    return road_map

You are returning immediately after you consume the first line. This is why it only prints the very first line.

Instead, you need to store these in a list, and return that list in the end.

def read_cities(file_name):
    file_name = open('city-data.txt' , 'r')
    road_maps = []
    for line in file_name:
        road_map = ((line.split('\t')))
        road_maps.append(road_map)
    file_name.close()
    # road_maps is a list, since you wanted a tuple we convert it to that
    return tuple(road_maps)

print(read_cities('city-data.txt'))

I need to create a tuple of all the states.

Does this mean you only want the first column from each line ? If so, modify it to

def read_cities(file_name):
    # notice I've changed this to use file_name instead of 
    # the hard-coded filename string
    file_name = open(file_name , 'r')

    # if you need uniqueness, use states=set() and use .add instead
    # of .append
    states = []

    for line in file_name:
        line_split = line.split('\t')
        # line_split is a list and the 0th index is the state column
        state = line_split[0]
        # use states.add if you used a set instead of a list
        states.append(state)

    file_name.close()
    return tuple(states)

print(read_cities('city-data.txt'))

Upvotes: 1

Related Questions