2016-09-27 187 views
1

我似乎无法将每个单行从.txt文件拉到元组中。 'city-data.txt'文件只是50个州,capitols和他们经纬度的列表。我需要创建一个所有状态的元组。从另一个文件读取多行到一个元组

这是到目前为止我的代码 -

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')) 

当它运行时,只打印从.txt文件的第一行,因为这样的:

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

在您的函数中用'yield'替换'return'然后将其包装在一个循环中... – dawg

回答

1

只打印的原因的第一行是因为这个

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

你消耗的第一行后,您会立即返回。这就是为什么它只打印第一行。

相反,您需要将它们存储在列表中,并在最后返回该列表。

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')) 

我需要创建的所有状态的元组。

这是否意味着您只需要每行的第一列?如果是这样,修改它为

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')) 
相关问题