thefoodiee
thefoodiee

Reputation: 13

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

Currently I am working on a python password manager. 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. 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.

Upvotes: 1

Views: 1181

Answers (1)

Edo Akse
Edo Akse

Reputation: 4401

Some string.split() magic will resolve this. I added some logic to be able to deal with usernames or passwords containing the - character

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
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

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'}

Upvotes: 1

Related Questions