简体   繁体   中英

how can i replace something inside a txt file (python)

i am trying to replace something in my txt file without deleting anything else in that file. so i want to split at the "=" sign and then replace everything that comes after it with a variable called "new_balance"

        with open("{}'s Account.txt".format(ctx.author)) as f:
            for line in f.readlines():
                fragments = line.split("=", maxsplit=1)
                candidate = fragments[0].strip()
                if candidate == "Coins":
                    if candidate in line:
                        line = line.replace(fragments[1], new_balance)
                    sys.stdout.write(line)

my txt file looks something like this: verified! Coins=0 Attack=0 Defense== verified! Coins=0 Attack=0 Defense==

everything that comes after Coins= should be replaced with the new_balance variable

temp = []
temp = line.split("=", maxsplit=1)
line = temp[0] + "=" + str(new_balance) + " " + temp[1].split(" ", maxsplit=1)[1]

temp output: ['verified, Coins', '0 Attack', '0 Defense', '', '']

line output: verified! Coins=1 Attack=0 Defense==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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