0

所以我想做的是将我所有的用户名和密码从一个文本文件加载到一个字典中来调用它们......

     def createacc():
                x = 0
                while x != 200:
                    print("\n")
                    x+=1
                answer = {}
                error = None
                with open('usernames.dat', 'r') as document:
                    for line in document:


                        n = line.replace("\n'","")

                        arts = n.replace("[","")

                        parts = arts.replace("['","")

                        nparts = parts.split("=")

                        line = parts


                        if not line:  # empty line?
                            continue
                        answer[line[0]] = line[1:]
                print("\n\n\n\n\n")
                print(answer)
                print("\n\n\n\n\n")


                if request.method == "POST":
                    if request.form['username'] == '' or request.form['password'] == "" or request.form['code'] != "30286":
                        error="Faliure to create account!! please try again"
                    else:
                        acc = open("usernames.dat","a+")

                        a = acc.readlines()
                        aaa = request.form['username'] +"="+ request.form['password'] + "\n"
                        acc.writelines(aaa)
                        acc.close()
                        return redirect(url_for('sms'))
                return render_template('newacc.html',error=error)

我希望我的字典看起来像这样

{'admin':'admin', 'PPGC': 'Default', 'DELTA': 'Readme'}

我得到的结果是

{'a': 'dmin=admin\n', 'P': 'PGC\n', 'D': 'ELTA\n', 'N': 'AVI\n'}

我需要做什么才能得到我想要的字典?

4

1 回答 1

2

您的程序是否在文本文件中写入用户名、密码?如果是,我建议使用 JSON 或任何其他数据交换格式。例如,使用 json 你可以做到这一点

import json

user_dict = {'some user': 'some password'}

with open('my_database.json', 'w') as db:
    json.dump(user_dict, db)

# Now the data can be can easily loaded
user_data = json.load(open('my_database.json'))

# This will get you the dictionary back. 
于 2013-10-10T03:09:30.653 回答