简体   繁体   English

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

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

Currently I am working on a python password manager.目前我正在开发一个 python 密码管理器。 Its not too complex, just a simple commandline interface.它不是太复杂,只是一个简单的命令行界面。 I have made one file in which the passwords and usernames are stored in the following format:我制作了一个文件,其中密码和用户名以以下格式存储:

servicenameusername-usernameinput
servicenamepassword-generatedpassword

for eg:例如:

GOOGLEusername-myusername
GOOGLEpassword-generated password

The problem is that when I try to fetch the password and username from a separate program.问题是当我尝试从单独的程序中获取密码和用户名时。 I need a way to slice a line in the txt file.我需要一种在 txt 文件中切片的方法。 eg:例如:

GOOGLEpassword-passowrd
GOOGLEusername-username

I want the program to get the service name as input and then return what is in front of them.我希望程序获取服务名称作为输入,然后返回它们前面的内容。 I need to slice it in such a way that it takes the first character of the password and prints it until the line ends.我需要以这样一种方式对其进行切片,即它需要密码的第一个字符并打印它直到行结束。 Thanks in advance.提前致谢。

Some string.split() magic will resolve this.一些string.split()魔法将解决这个问题。 I added some logic to be able to deal with usernames or passwords containing the - character我添加了一些逻辑来处理包含-字符的用户名或密码

password.py密码.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测试1.txt

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

output输出

[{'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': 'STACKOVERFLOW',
  'username': 'testing'}]
----------


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

Original answer原答案

password.py密码.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'))

output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从前缀为 Python 的文本文件中切片数据? - How do I slice data from a text file with a prefix in Python? 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python 如何从Python中的特定文本行中提取文本? - How do I pull text from a specific text line in Python? 如何根据文本而不是字母编号对 python 中的字符串进行切片? - How do I slice a string in python based on the text, not the letter number? 如何使用python删除文本文件中的行? - How do I delete a line in a text file using python? 我如何从 python 中的文本文件中删除换行符,以便更容易使用 - how do i remove line breakes from a text file in python so its easier to work with 我如何使用文本文件中的一行作为python中的函数输入? - how do i use a line from a text file as a function input in python? Python 2:在从包含该字符串的文本文件返回整行之前,如何在文本文件中搜索字符串? - Python 2: How do I search for a string in a text file before returning the entire line from the text file that contains this string? 我如何从 python 中的特定行读取文本文件? - How i can Read text file from a specific line in python? 如何使用 python 从一行中剪切文本并将 append 剪切到文本文件中的另一行? - How do you cut text from a line and append it to another line in text file using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM