2016-09-27 133 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')) 
相關問題