简体   繁体   English

在已加载的文本文件中执行数学方程式

[英]Perform math equation inside of a loaded text file

I'm currently working on a simple little application that keeps track of wins and losses for any sort of game. 我目前正在开发一个简单的小应用程序,该应用程序可以跟踪任何类型的游戏的成败情况。 I'm storing the win/loss count in separate text files as single numbers. 我将获胜/亏损计数作为单个数字存储在单独的文本文件中。 What I want the program to be able to do is look into the specified text file, and simply add 1 to the existing number. 我希望程序能够执行的操作是查看指定的文本文件,然后简单地在现有数字上加1。 For example, if the entire text file is simply "0" and I input "win" into the application, it will perform 0+1 and change the text file permanently to the result. 例如,如果整个文本文件只是“ 0”,而我在应用程序中输入“ win”,它将执行0 + 1并将文本文件永久更改为结果。 Here's what I've got so far: 到目前为止,这是我得到的:

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("")

Everything I've done so far is in the first if statement. 到目前为止,我所做的一切都在第一个if语句中。 I'm not getting any error when I run the code, even when I input "w", but the number in the text file doesn't change. 即使我输入“ w”,运行代码时也不会出现任何错误,但文本文件中的数字不会更改。 Thanks in advance for any help, and I'll stay on the page to answer any questions that may help you figure out what's wrong. 在此先感谢您的帮助,我们将继续在页面上回答所有可能帮助您找出问题所在的问题。

I would recommend using a single file database like SQLIte instead of separated text files. 我建议使用像SQLIte这样的单个文件数据库,而不要使用单独的文本文件。 You also can register all wins and losses (with timestamp, if you needed later). 您还可以注册所有的胜利和失败(带有时间戳,如果以后需要的话)。

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)

And it is easier to read and understand 而且更容易阅读和理解

As you seem to have very small data in your lossdata.txt and windata.txt, I would preferably do the following : 由于您的lossdata.txt和windata.txt中的数据似乎很少,我最好执行以下操作:

  • read the entire file content and store the data into variables (open the file in readmode, read data, then close the file), 读取整个文件内容并将数据存储到变量中(以读取模式打开文件,读取数据,然后关闭文件),
  • overwrite the entire file content with the new value (open the file in writemode, write data, then close the file) 用新值覆盖整个文件内容(以writemode打开文件,写入数据,然后关闭文件)

If you need to update a particular line of your file, know that it's better to make a copy of your input file and create the updated file as a new file. 如果需要更新文件的特定行,请知道最好复制输入文件并将更新后的文件创建为新文件。 This is exactly what fileinput.input(inplace=1) does as noted in this SO answer . 正如这个SO Answer所指出的, 正是fileinput.input(inplace=1)所做的。

So, try to do something like : 因此,尝试执行以下操作:

import fileinput

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM