获取文件名并将该文件的内容读入2个列表

时间:2015-11-05 06:57:49

标签: python

我已经定义了2个列表,我想将文本文件的内容读入下面显示的2个列表中。我不知道如何构造代码,以便将文本文件中的名称和数字调用到列表中?

def read_file(filename, player_names, player_scores):

    infile = open("high_scores.txt", "r")

    infile.close()

定义列表

player_names = ["","","","",""]
player_scores = [0,0,0,0,0]
print('Player_names',player_names)
print('Player_scores',player_scores)

1 个答案:

答案 0 :(得分:1)

考虑您的输入文件是一个以玩家和分数分隔的标签

  

player1 100

     

player2 50

     

player3 65

您的工作代码将是

def read_file(filename, player_names, player_scores):
    with open(filename, "r") as infile:
        for line in infile:
            player_score = line.split('\t')
            player_names.append(player_score[0])
            player_scores.append(int(player_score[1]))


if __name__ == "__main__":
    player_names = []
    player_scores = []
    read_file('high_scores.txt', player_names, player_scores)
    print('Player_names',player_names)
    print('Player_scores',player_scores)

这将是你的输出:

  

(' Player_names',[' player1',' player2',' player3'])

     

(' Player_scores',[100,50,65])