Python脚本可以写入文件,但同一行不能在以后的代码中写入

2024-04-24 07:28:48 发布

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

在我写入字符串时的代码开头:

                        #write username and skill level to file
                    f = open("ArenaList.txt","a")
                    f.write(user + " " + str(health) + '\n')
                    Parent.RemovePoints(user, settings["cost"])
                    f.close()

那很好用

在后面的代码中,我试图找到一行包含用户名和任何健康值的内容,然后编辑健康值,它根本无法写入,我不明白为什么:

                                with open("ArenaList.txt","r") as search:
                                    for line in search:
                                            if user in line:
                                                    strLine = ("{}".format(line))
                                                    health = (("{}".format(line)).split(' ', 1)[-1])
                                                    name = (("{}".format(line)).split(' ')[0])
                                                    inthealth = int(health)
                                                    inthealth = (inthealth + 5)
                                                    Parent.SendTwitchMessage(user + " " + str(inthealth))
                                                    search.write(user + " " + str(inthealth) + '\n')

                                            else:
                                                    search.close()

我得到的错误是“无法写入文件ArenaList.txt”

谢谢你的帮助! 编辑:我很笨,打开文件的位是“r”用于读取。我不知道如何使它既能读又能写


Tags: 代码txtformat编辑closesearchlineopen
1条回答
网友
1楼 · 发布于 2024-04-24 07:28:48

您必须先读取文件,然后写入(覆盖任何现有数据),而无需关闭或重新打开:

with open("ArenaList.txt","r+") as search:
    # some code
    # now to write do this
    search.seek(0)
    search.write("something")

相关问题 更多 >