如何获取文本文件并将其转换为python中的字典

时间:2013-10-10 02:55:51

标签: python dictionary text-files

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

     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'}

我需要做什么才能获得我想要的词典?

1 个答案:

答案 0 :(得分: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.