首页 > 解决方案 > 高分文件:将字符串列表转换为整数列表会导致 int() 以 10 为底的无效文字:''

问题描述

所以我一直在创建一个骰子游戏,其中有一个必须存储在文本文档中的名称和分数。但随后会打印前 5 个高分和名称。

这是我当前的代码:

#input of new score and name
score = input('score: ')
name = input('Name: ')
#storing it
f = open('scores.txt','a+')
f.write(score)
f.write(',')
f.write(name)
f.write(',')
f.close()
#reading the file with , as a split so forming a list
f = open('scores.txt','r')
content = f.readline()
data = content.split(",")
#extracting the numbers from the original list
numdata = data[::2]
#converting the numbers from a string to an int
for i in range(len(numdata)):
    numdata[i] = int(numdata[i])
#ordering the numbers
numdata = map(int, numdata)
numdata = sorted(numdata, reverse=True)

#then some test prints of the first 5 scores
#i will add the names back to the scores after i have sorted this list issue

f.close()

所以我存储了分数和名称,用逗号分隔所有值。我已经成功地从 txt 文件中读取了它,并将原始列表中的数字提取到一个新列表中 - 然后排序 - 但是在尝试排序时,它将数字排序为字符串,所以我编辑了我的代码,所以它排序为整数. 但这就是问题来的时候,该列表是一个字符串列表,它不能按整数排序。所以我用

for i in range(len(numdata)):
    numdata[i] = int(numdata[i])

但是,这也不起作用,并且给了我与没有它时相同的错误代码。这是错误(我已经搜索了如何纠正它,但我没有尝试过)

invalid literal for int() with base 10: ''

想知道是否有人知道如何解决这个问题。

标签: pythonpython-3.x

解决方案


您可能希望使用with open(...):. 您的错误源于最后一行之后的非空行,您可以.strip()

也许阅读 csv-module 并创建一个 csv 风格的高分 - 文件:


import csv
filename = "scores.txt"

def sortScores(s):
    return sorted(s, key = lambda x: x[1], reverse=True)

# write values
def writeScores(fn,s):
    with open(fn,"w",newline="") as f:
        csvwriter=csv.writer(f)
        # sort highest first
        for name,points in sortScores(s):
            csvwriter.writerow([name,str(points)])

# restore values
def readScores(fn): 
    scores_from_file = []
    with open(fn,"r",newline="") as f:
        csvreader=csv.reader(f)
        for row in csvreader:
            scores_from_file.append( (row[0],int(row[1])) )
    return scores_from_file

# game internal data-structure as list of tuples to enable identical names
scores= [("Egon",243), ("Phil",42), ("Angus",999)]

writeScores(filename,scores)

# print file content
with open(filename,"r") as f:
    print(f.read())

scores_from_file = readScores(filename)   

print(scores_from_file)

写入后的文件内容:

Angus,999
Egon,243
Phil,42

阅读后的内容scores_from_file(由于排序写入而排序):

[('Angus', 999), ('Egon', 243), ('Phil', 42)]

推荐阅读