如何从 python 中的文本文件中切出一行?

How do I slice a line from a text file in python?

目前我正在开发 python 密码管理器。它不太复杂,只是一个简单的命令行界面。我制作了一个文件,其中以下列格式存储密码和用户名:

servicenameusername-usernameinput
servicenamepassword-generatedpassword

例如:

GOOGLEusername-myusername
GOOGLEpassword-generated password

问题是当我尝试从一个单独的程序中获取密码和用户名时。我需要一种在 txt 文件中分割一行的方法。 例如:

GOOGLEpassword-passowrd
GOOGLEusername-username

我希望程序获取服务名称作为输入,然后return它们前面的内容。我需要以这样一种方式对其进行切片,即它采用密码的第一个字符并打印它直到该行结束。提前致谢。

一些 string.split() 魔法可以解决这个问题。我添加了一些逻辑来处理包含 - 字符

的用户名或密码

password.py

from pprint import pprint


def process_two_lines(line1: str, line2: str) -> dict:
    # determine which of the 2 variables is the password
    # and which is the username
    if 'password' in line1.split('-')[0]:
        passwordline = line1
        userline = line2
    else:
        passwordline = line2
        userline = line1
    
    # the join is in case the password or username contains a "-" character
    password = '-'.join(passwordline.split('-')[1:]).strip('\n') 
    username = '-'.join(userline.split('-')[1:]).strip('\n')
    service = userline.split('username')[0]
    return {
        'username': username,
        'password': password,
        'service':  service
    }    


def get_login_info(filename: str) -> dict:
    # read file
    with open(filename) as infile:
        filecontents = infile.readlines()
    
    result = []
    # go through lines by pair
    for index, line1 in enumerate(filecontents[::2]):
        result.append(process_two_lines(line1, filecontents[(index*2)+1]))

    return result



logininfo = get_login_info('test1.txt')
pprint(logininfo)
print('----------\n\n')

for index, line in enumerate(logininfo):
    print(f'{index:2}: {line["service"]}')


service = int(input('Please select the service for which you want the username/password:\n'))

print(f'Username:\n{logininfo[service]["username"]}\nPassword:\n{logininfo[service]["password"]}\n')

test1.txt

TESTACCOUNTusername-test-user
TESTACCOUNTpassword-0R/bL----d?>[G
GOOGLEusername-google
GOOGLEpassword-V*biw:Y<%6k`?JI)r}tC
Whosebugusername-testing
Whosebugpassword-5AmT-S)My;>3lh"

输出

[{'password': '0R/bL----d?>[G',
  'service': 'TESTACCOUNT',
  'username': 'test-user'},
 {'password': 'V*biw:Y<%6k`?JI)r}tC',
  'service': 'GOOGLE',
  'username': 'google'},
 {'password': '5AmT-S)My;>3lh"',
  'service': 'Whosebug',
  'username': 'testing'}]
----------


 0: TESTACCOUNT
 1: GOOGLE
 2: Whosebug
Please select the service for which you want the username/password:
2
Username:
testing
Password:
5AmT-S)My;>3lh"

原回答

password.py

from pprint import pprint

def get_login_info(filename: str) -> dict:
    with open(filename) as infile:
        filecontents = infile.readlines()
    for line in filecontents:
        if 'password' in line.split('-')[0]: # split needed to not get false positive if username == password
            password = line.split('-')[1].strip('\n') # gets the part after the - separator, removing the newline
            service = line.split('password')[0] # gets the service part
        elif 'username' in line.split('-')[0]: # split needed to not get false positive if password == username
            username = line.split('-')[1].strip('\n')
    result = {
        'username': username,
        'password': password,
        'service':  service
    }    
    return result

pprint(get_login_info('test0.txt'))
pprint(get_login_info('test1.txt'))

输出:

{'password': 'generatedpassword',
 'service': 'servicename',
 'username': 'usernameinput'}
{'password': 'generated password',
 'service': 'GOOGLE',
 'username': 'myusername'}