将文件中的一行拆分为不同的列表

时间:2014-11-02 20:37:44

标签: python list python-2.7 dictionary

我的程序应该从用户那里获取输入并读取名称为input的文件。读取文件被保存到一个名为portfolio的字典中,从那里我要做的就是将组合中的每一行分类为键和值。

这是我的代码。

portfolio = {}
portfolio = file_read() #Reads the file through a function
if file_empty(portfolio) == True or None: #nevermind this, it works
    print "The file was not found."
else:
    print "The file has successfully been loaded"

for line in portfolio:
    elements = line.strip().split(",") #separate lists by comma
    print elements[0] #using this to check
    print elements[1] #if it works at all

所有这一切都是打印第一行中的第一个字母,即S.显然元素[1]应该是第二个字母,但索引超出范围,请告诉我可能出错的地方。

谢谢。

2 个答案:

答案 0 :(得分:0)

看起来file_read()正在将文件读入字符串。

然后for line in portfolio:正在遍历该字符串中的每个字符

然后elements = line.strip().split(",")将为您提供一个包含一个字符的列表,因此尝试获取elements[1]超出了列表的范围。

如果要将文件的全部内容读入名为portfolio的字符串,可以使用

遍历字符串中的每个
for line in porfolio.split('\n'):
    ...

但是,更常用的方法是迭代文件中的行

with open(filename,'r') as inputfile:
    for line in inputfile:
         ....

答案 1 :(得分:0)

使用此代码:

    for line in minfil :
    line = line.strip()
    elements = line.split(",")
    portfolio[str(elements[0])] = [(int(elements[1]),float(elements[2]), str(elements[3]))]   
相关问题