来自txt文件的变量

时间:2016-04-19 11:35:41

标签: python python-3.x

我有一个txt文件,用于存储具有以下内容的Show virtual space at file bottom测试的用户ID:

Selenium

并希望将我的txt文件中admin = ['admin@admin.com', 'password1234'] basicUser = ['basic@basic.com', 'password1234'] / admin的值分配给我的Python脚本,如下所示:

basicUser

每当我为我的LoginPage调用import file.txt file = open('file.txt', 'r') admin = file(admin) basicUser = file(basicUser) 方法时

changePassword

它会自动更新并保存txt文件以供下次登录。

我已经浏览了几个小时的论坛,无法找到任何好的/优雅的解决方案,任何想法?

2 个答案:

答案 0 :(得分:2)

您可以使用.yaml文件来存储您的用户。它以json格式存储您的数据。

admin: {passwd: 123, user: admin@admin.com}
basicUser: {passwd: pass45, user: basic@basic.com}

从文件中加载用户:

import yaml
with open(FILE_PATH, 'r') as f:
   users_dict = yaml.load(f)
print(users_dict)
print(users_dict['admin'])
### {passwd: 123, user: admin@admin.com}
print(users_dict['admin']['passwd'])
### 123

加载后,您可以像dict一样处理数据

保存用户数据:

users_dict['admin']['passwd'] = 345

with open(FILE_PATH, 'w') as f:
   yaml.dump(users_dict, f)

答案 1 :(得分:0)

您可以像这样轻松地保留当前的文件格式:

import re
load_pattern = r"^(\w+)\s*=\s*\[\s*'(.+?)'\s*,\s*'(.+?)'\s*\]$"
save_pattern = "{} = ['{}', '{}']"

def load_users(filename):
    users = {}
    with open(filename), as f:
        for line in f:
            try:
                name, email, pw = re.fullmatch(load_pattern, line.strip()).groups()
                users[name] = [email, pw]
            except AttributeError:
                pass  # do nothing if the line does not match our pattern
    return users

def save_users(users, filename):
    with open(filename, "w") as f:
        for name in users:
            email, pw = users[name]
            print(save_pattern.format(name, email, pw), file=f)

如何使用它:

# Load user dictionary from file:
users = load_users("file.txt")

# Iterate over all stored users:
for name in users:
    # Print each user's data:
    print("Username:    ", name)
    print(" -> Email:   ", users[name][0])
    print(" -> Password:", users[name][1])

    # Change each user's password in our dictionary to the capitalized username:
    users[name][1] = name.upper()

# Save the changed user information to a file 
# (creates new file or overwrites old one if already existing):

save_users(users, "file2.txt")