首页 > 解决方案 > How to put certain instances of a text file to a list in python

问题描述

This is what a part of the txt file looks like:

3/Kingsbury Dr/Waterdale Rd/Bundoora

4/Crissane Rd/Waterdale Rd/Heidelberg West

I just want to get the second element which is the bus stop (eg Kingsbury Dr, Crissane Rd) instance in a list. Here is what I have tried so far and not sure how to put the second element in a list

def loadData():
    with open('BusRoute250.txt', 'r') as f:
        busStopList = []
        f_line = f.readline()
        while f_line:
            file_line_lst = list(f_line.strip().split('/'))
            f_line = f.readline()
            for f_line in file_line_lst:
                busStopList.append()
                print(busStopList)

The link for txt file contents: https://docs.google.com/document/d/1ah1EAhro_5-pgqIDylFSjTyHI9fvylfErB8pFNZb36A/edit?usp=sharing

标签: python

解决方案


You need to add the second element of the list formed in the result of split('/') operation.

busStopList.append(file_line_lst[1])

The while loop is a bit wrong. It should be like this:

while f_line:
    file_line_lst = list(f_line.strip().split('/'))
    busStopList.append(file_line_lst[1])
    f_line = f.readline()

推荐阅读