簡體   English   中英

如何從python中文件的最后一行讀取第一個字符

[英]How to read a first character from the last line of a file in python

我正在用 python 編寫記分牌(我對這門語言還很陌生)。 基本上用戶輸入他們的名字,我希望程序讀取文件來確定分配給用戶的號碼。

  • 例如,.txt 文件中的名稱是:
  • 數字名稱分數
    1. 約翰·多伊 3
    1. 米奇 5
    1. 簡 1

我現在如何添加 4 號用戶,而無需用戶鍵入要寫入的確切字符串,只輸入他們的姓名。

非常感謝!

我建議重新考慮您的設計 - 您可能不需要文件中的行號,但是您可以閱讀文件並查看有多少行。

如果您最終獲得大量數據,這將無法擴展。

>>> 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)是你需要的。

獲取行數的最簡單方法是使用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()
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()

謝謝各位,我想通了。 這是我將新用戶添加到列表的最終代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM