如何在python中从文件的最后一行读取第一个字符
我正在用python编写记分板(我对该语言相当陌生)。基本上,用户输入他们的名字,我希望程序读取文件来确定,用户被分配到的号码如何在python中从文件的最后一行读取第一个字符,python,Python,我正在用python编写记分板(我对该语言相当陌生)。基本上,用户输入他们的名字,我希望程序读取文件来确定,用户被分配到的号码 例如,.txt文件中的名称为: Num名称分数 无名氏3 米奇5 简1 我现在如何添加4号用户,而不让用户键入要写入的确切字符串,仅输入其名称 非常感谢 我建议重新考虑您的设计-您可能不需要文件中的行号,但是您可以阅读文件并查看有多少行 如果你最终拥有大量数据,这将无法扩展 >>> with open("data.txt") as f:
- 例如,.txt文件中的名称为:
- Num名称分数
- 无名氏3
- 米奇5
- 简1
非常感谢 我建议重新考虑您的设计-您可能不需要文件中的行号,但是您可以阅读文件并查看有多少行 如果你最终拥有大量数据,这将无法扩展
>>> 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()