我正在python中写一个记分板thingie(我对这个语言相当陌生)。基本上用户输入他们的名字,我希望程序读取文件以确定用户被分配的号码。如何从python文件的最后一行读取第一个字符
- 例如,在.txt文件的名称是:
- 货号名称分数
-
- John Doe的3
-
- 米奇5
-
- 珍1
我现在该如何,而无需用户输入的准确字符串写的,只有自己的名字添加用户四号。
非常感谢!
我正在python中写一个记分板thingie(我对这个语言相当陌生)。基本上用户输入他们的名字,我希望程序读取文件以确定用户被分配的号码。如何从python文件的最后一行读取第一个字符
我现在该如何,而无需用户输入的准确字符串写的,只有自己的名字添加用户四号。
非常感谢!
我建议重新考虑一下你的设计 - 你可能不需要文件中的行号,但是你可以只读这个文件,看看有多少行。
如果最终得到大量数据,这将不会扩展。
>>> with open("data.txt") as f:
... l = list(f)
...
这将读取头
>>> l
['Num Name Score\n', 'John Doe 3\n', 'Mitch 5\n', 'Jane 1\n']
>>> len(l)
4
所以len(l)-1
是最后一个号码,len(l)
是你所需要的。
def add_user():
with open('scoreboard.txt', 'r') as scoreboard:
#Reads the file to get the numbering of the next player.
highest_num = 0
for line in scoreboard:
number = scoreboard.read(1)
num = 0
if number == '':
num == 1
else:
num = int(number)
if num > highest_num:
highest_num = num
highest_num += 1
with open('scoreboard.txt', 'a') as scoreboard: #FIle is opened for appending
username = input("Enter your name!")
scoreboard.write(str(highest_num) + '. ' + str(username) + ": " + '\n')
scoreboard.close()
谢谢你们,我想通了。这是我添加新用户到列表的最终代码。
获得的行数的最简单的方法是使用readlines()
x=open("scoreboard.txt", "r")
line=x.readlines()
lastlinenumber= len(line)-1
x.close()
with open('scoreboard.txt', 'a') as scoreboard: #FIle is opened for appending
username = input("Enter your name!")
scoreboard.write(str(lastlinenumber) + '. ' + str(username) + ": " + '\n')
scoreboard.close()
这是一样的。我们知道许多行的文件如何 - 除了列标题,即数量仅仅是多了一个针对每个线? – doctorlove
将此号码保存在其他文件中。或者保留没有这个数字的行 - 你不需要它们。 – furas