[英]Reading in 2 Arrays from a file
How would I read in from a file and separate it into an array?我将如何从文件中读取并将其分成一个数组? Example inside the file
文件内的示例
test1:test1测试1:测试1
test2:test2测试2:测试2
read into array line by line user[] pass[]逐行读入数组 user[] pass[]
with open("acc.txt") as f:
for line in f:
username, password = line.split(':')
content_array.append(line)
print(username)
A dictionary is probably the best data structure this, here are two ways to do it:字典可能是最好的数据结构,这里有两种方法:
def open_txt(path):
with open(path) as file:
return file.read()
acc = open_txt('./acc.txt')
acc_dict = {line.split(':')[0]: line.split(':')[1]
for line in acc.splitlines()}
acc_dict_list = [{'name': line.split(':')[0],
'pass': line.split(':')[1]}
for line in acc.splitlines()]
print(f'acc_dict: {acc_dict}')
print(f'acc_dict_list: {acc_dict_list}')
Input (acc.txt):输入(acc.txt):
user1:pass654321
user2:pass123456789
user3:pass987654321459
Output: Output:
acc_dict: {'user1': 'pass654321', 'user2': 'pass123456789', 'user3': 'pass987654321459'}
acc_dict_list: [{'name': 'user1', 'pass': 'pass654321'}, {'name': 'user2', 'pass': 'pass123456789'}, {'name': 'user3', 'pass': 'pass987654321459'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.