[英]How do I take a text file and turn it into a dictionary in python
So what I am trying to do is load up all my usernames and passwords from a textfile into a dictionary to call upon them... 所以我想做的是将我所有的用户名和密码从一个文本文件加载到字典中以调用它们...
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)
And What I was hoping my dictionary out would look like would be like so 我希望我的字典看起来像这样
{'admin':'admin', 'PPGC': 'Default', 'DELTA': 'Readme'}
and the result I am getting is 我得到的结果是
{'a': 'dmin=admin\\n', 'P': 'PGC\\n', 'D': 'ELTA\\n', 'N': 'AVI\\n'}
What do I need to do to get my desired dictionary? 我需要怎么做才能得到想要的字典?
Is your program writing the username, passwords in a textfile? 您的程序是否在文本文件中写入用户名和密码? If yes, I would suggest to use JSON or any other data interchange format.
如果是,我建议使用JSON或任何其他数据交换格式。 For example, with json you can do this
例如,使用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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.