我正在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