读取文件并返回国家列表的方法

时间:2015-11-10 09:48:08

标签: python list file-io casting

我正在努力研究一种读取文件(包含一堆国家名称)的方法,并返回这些国家的列表。

example:(lets say we have a file "file.txt",it contains the following)

    Afghanistan,    647500.0,   25500100
    Albania,    28748.0,    2821977
    Algeria,    2381740.0,  38700000 
    .......(and so on)
    Zimbabwe,   390580.0,   12973808
我写下了一个方法:

def readCountries(filename):
    open_file = open(filename, 'r')
    new_list = []
    contents = open_file.readlines()
    for i in range(len(contents)):
         new_list.append(contents[i].split())
    return new_list    
    open_file.close()

此方法返回输出:

[['Afghanistan,', '647500.0,', '25500100'], ['Albania,', '28748.0,', '2821977'], .......['Zimbabwe,', '390580.0,', '12973808']] 

相反,我希望它是这样的:

[["Afghanistan",647500.0,25500100],["Albania",28748.0,2821977],...,["Zimbabwe",390580.0,12973808]]

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

def readCountries(filename):
    open_file = open(filename, 'r')
    new_list = []
    contents = open_file.readlines()
    for i in range(len(contents)):
         lsSplit = contents[i].split(",")
         new_list.append([lsSplit[0], float(lsSplit[1].strip()), int(lsSplit[2])])
    open_file.close()
    return new_list