在加载的文本fi中执行数学公式

2024-10-01 19:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在开发一个简单的小应用程序,它可以记录任何类型游戏的输赢情况。我将赢/输计数作为单个数字存储在单独的文本文件中。我希望程序能够做的是查看指定的文本文件,并在现有的数字上加1。例如,如果整个文本文件只是“0”,而我在应用程序中输入“win”,它将执行0+1并将文本文件永久更改为结果。 到目前为止,我得到的是:

ld = open("data/lossdata.txt", "r+")
wd = open("data/windata.txt", "r+")
hlp = open("data/help.txt", "r+")
losread = ld.read()
winread = wd.read()
helpread = hlp.read()
to_write = []

print("Welcome to Track Lad. For help, input \"help\"\nCurrent Win Count: "+winread+"\nCurrent Loss Count: "+losread)
inp = input("Input: ")

if inp == "w" or inp == "win":
    for line in wd:
        num = int(line) + 1
        to_write.append(num)
        wd.reload()
    wd.seek(0)
    for num in to_write:
        wd.write(str(num)+'\n')
    wd.close()
    print("New Win Count: "+winread+"\nLoss Count: "+losread)
    input("")
elif inp == "l" or inp == "loss":
    ld.write("1")
    print("New Loss Count: "+losread+"\nWin Count: "+winread)
    input("")
elif inp == "help":
    print(helpread)
    input("")
else:
    print("Invalid input, try again.")
    input("")

到目前为止我所做的一切都在第一个if语句中。我在运行代码时没有得到任何错误,即使我输入“w”,但是文本文件中的数字没有改变。提前感谢您的帮助,我会在页面上回答任何可能帮助您找出问题所在的问题。在


Tags: toinputcounthelp数字opennumwrite
2条回答

我建议使用单个文件数据库,比如SQLIte,而不是单独的文本文件。你也可以登记所有的胜负(如果你以后需要的话,可以加上时间戳)。在

import sqlite3

db = sqlite3.connect('winloss.db')
cursor = db.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS winloss (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        t TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        value TEXT
    );
''')
db.commit()


def add_value(db, value):
    cursor = db.cursor()
    cursor.execute("INSERT INTO winloss(value) VALUES(?)", (value, ))
    db.commit()


def add_win(db):
    add_value(db, "win")


def add_loss(db):
    add_value(db, "loss")


def count_value(db, value):
    cursor = db.cursor()
    cursor.execute("SELECT COUNT(*) FROM winloss where value=?", (value, ))
    return cursor.fetchone()[0]


def count_win(db):
    return count_value(db, "win")


def count_loss(db):
    return count_value(db, "loss")


if __name__ == '__main__':
    print "now"
    print "win:", count_win(db)
    print "loss:", count_loss(db)
    print "adding values"
    add_win(db)
    add_win(db)
    add_loss(db)
    print "win:", count_win(db)
    print "loss:", count_loss(db)

而且更容易阅读和理解

因为你在你的损失数据.txt以及温达.txt,我最好做以下事情:

  • 读取整个文件内容并将数据存储到变量中(以readmode打开文件,读取数据,然后关闭文件)
  • 用新值覆盖整个文件内容(在writemode中打开文件,写入数据,然后关闭文件)

如果您需要更新文件的某一行,那么最好复制一个输入文件并将更新后的文件创建为新文件。这正是^{}所做的,正如this SO answer中所述。在

所以,试着做些类似的事情:

import fileinput

def process(line):
    return int(line) + 1

for line in fileinput.input(inplace=1):
    print process(line)

相关问题 更多 >

    热门问题