编辑特定于文本文件的行

时间:2017-07-16 14:10:40

标签: python-3.x

我正在创建数学测验并需要在登录表中添加分数。文本文件行如下所示:名称,用户名,密码

我想知道你是否能够编辑这行,所以它看起来像这样:姓名,用户名,密码,尝试1 = 12

姓名,用户名,密码,尝试1 = 12,尝试2 = 23等等

感谢Adam的帮助

顺便说一句,这就是我找到这条线的方式:

 lookup = Name   
 with open("users.txt") as myFile:
    for num, line1 in enumerate(myFile, 1):
        if lookup in line1:
            line = line1

2 个答案:

答案 0 :(得分:0)

虽然这可能不是我回答的答案。如果这不符合您的需求,请忽略。仅仅是我评论的一个例子。

这是另一种存储信息的方法。 想一下所有键都是用户名的字典:

usernames.json

<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">
<entity name="new_creditmemo">
<attribute name="new_creditmemoid"/>
<attribute name="new_name"/>
<attribute name="new_customerno"/>
<attribute name="new_customername"/>
<order descending="false" attribute="new_name"/>
    <link-entity name="new_creditmemoline" link-type="outer" to="new_creditmemoid" from="new_creditmemoid">
    <attribute name="new_name"/>
    <attribute name="new_creditmemoid"/>
    <attribute name="new_locationcode"/>
    <attribute name="new_finalcmt"/>
    <order descending="false" attribute="new_name"/>
    </link-entity>
</entity>
</fetch> 

然后,您可以使用脚本(script.py)

加载数据
{
    "johnny": {
        "name": "John Doe",
        "password": "123",
        "attempts": [
            12,
            23
        ]
    },
    "foo": {
        "name": "Bar",
        "password": "345",
        "attempts": []
    }
}

阅读数据:

import json

with open("usernames.json") as f:
    mydict = json.load(f)

并添加数据:

print(mydict.keys()) # prints ["johnny","foo"]
print(mydict["johnny"]["attempts"]) #prints [12,23]

然后把它转回dict:

mydict["newuser"] = {"name":"hello","password":891,"attempts":[]} #adds new user
mydict["johnny"]["attempts"].append(15) # adds new attempt

答案 1 :(得分:0)

实际上,问题不是Python特有的。首先将文本文件(原则上)读入内存,然后修改内存内容并将其写回。

有可能在文件中找到某个位置并在那里写一个内容,但这会给你的案子带来更多问题。

您需要解决的第一件事是更多用户是否可以同时访问该文件。如果是,请想象两个用户想要读取 - 修改 - 写回的情况。其中一个值可能会“消失”。对于任何文件都是如此,包括推荐的.json解决方案。

我建议在你的应用程序中引入另一个层 - 包装修改对象(或函数)中的值 - 这将隐藏它的完成方式。稍后,您可以修改此实现以使用JSON,数据库或其他任何内容。

如果更多用户可以同时访问数据,那么简单的解决方案就是为每个用户使用一个带有单独文本文件的目录(一种简单的数据库)。