[英]Most efficient way to modify the last line of a large text file in Python
[英]most efficient way to convert text file contents into a dictionary in python
以下代码基本上执行以下操作:
我的问题是:是否有更简单,更有效(更快)的方法从文件内容创建字典:
文件:
user1,pass1
user2,pass2
码
def login():
print("====Login====")
usernames = []
passwords = []
with open("userinfo.txt", "r") as f:
for line in f:
fields = line.strip().split(",")
usernames.append(fields[0]) # read all the usernames into list usernames
passwords.append(fields[1]) # read all the passwords into passwords list
# Use a zip command to zip together the usernames and passwords to create a dict
userinfo = zip(usernames, passwords) # this is a variable that contains the dictionary in the 2-tuple list form
userinfo_dict = dict(userinfo)
print(userinfo_dict)
username = input("Enter username:")
password = input("Enter password:")
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
loggedin()
else:
print("Access Denied")
main()
要获得答案,请:
a)使用现有的函数和代码进行调整b)提供解释/注释(特别是使用split / strip)c)如果使用json / pickle,请包含初学者访问的所有必要信息
提前致谢
只需使用csv
模块 :
import csv
with open("userinfo.txt") as file:
list_id = csv.reader(file)
userinfo_dict = {key:passw for key, passw in list_id}
print(userinfo_dict)
>>>{'user1': 'pass1', 'user2': 'pass2'}
with open()
是用于打开文件的相同类型的上下文管理器,并处理关闭。
csv.reader
是加载文件的方法,它返回一个可以直接迭代的对象,就像在理解列表中一样。 但不是使用理解列表,而是使用理解词典。
要构建具有理解样式的字典,可以使用以下语法:
new_dict = {key:value for key, value in list_values}
# where list_values is a sequence of couple of values, like tuples:
# [(a,b), (a1, b1), (a2,b2)]
如果您不想使用csv
模块,您可以简单地执行以下操作:
userinfo_dict = dict() # prepare dictionary
with open("userinfo.txt","r") as f:
for line in f: # for each line in your file
(key, val) = line.strip().split(',')
userinfo_dict[key] = val
# now userinfo_dict is ready to be used
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.