从python文件中获取前5个值?

时间:2018-10-15 13:27:31

标签: python

所以我有一个列表,其中存储了两个变量,得分和每个玩家的用户名,如果我想从文件中选择前5个得分并打印出来,我将如何处理?

我现在想不出解决方案。

编辑: 目前,这是我必须写入存储分数的文件

def QuizEnd():
global points
points = str(points)
print('Thank you for playing,', login.username.title() + ', your score was:', points)
with open('scorefile.txt', 'r+') as scfile:
    scfile.write(login.username.title())
    scfile.write('-')
    scfile.write(points)
    scfile.write('\n')
    scfile.close

1 个答案:

答案 0 :(得分:1)

步骤1。这会将您的文本文件读取到df:

import pandas as pd
data = pd.read_csv('scoreline.txt', sep=" ", header=None) #sep depends on your file, it can be space, semicolon or anything.
data.columns = ["Score", "Username",] # Put names of your column 

第2步:找到数据df的前5行:

data.nlargest(5, columns=['Score'])