0

I want to split the lines in a file into 2 separate (2-dimensional) array.

E.g. Username : password array (users[user][pass])

This is the code I have come up with so far :

with open('userlist.txt', 'r') as userlist:
    for line in userlist:
        user, pwd = line.strip().split(':')
        users = [
             [user, pwd]
                ]

Please help. This code currently only lists all of the usernames and all of the passwords. But I want to be able to call the username with the password pair by the same index (e.g. print(users[1][1]))

4
  • 1
    Could you send an example string from userlist.txt? Commented Oct 9, 2018 at 13:06
  • You can use user = line.strip().split(':')[0] and pwd = line.strip().split(':')[1] IF your first column in the file is always user and the second is password Commented Oct 9, 2018 at 13:06
  • 1
    Pls provide sample input and output. array (users[user][pass]) is rather unclear. Commented Oct 9, 2018 at 13:06
  • Do you want [[user1, user2], [pwd1, pwd2]] or [[user1, pwd1], [user2, pwd2]]? Commented Oct 9, 2018 at 13:07

3 Answers 3

1

The following should suffice. Note that you have to initialize the outer data structure before the loop and fill it in the loop:

with open('userlist.txt', 'r') as userlist:
  users = []
  for line in userlist:
    users.append(line.strip().split(':'))

which can be shortened to:

with open('userlist.txt', 'r') as userlist:
  users = [line.strip().split(':') for line in userlist]
Sign up to request clarification or add additional context in comments.

Comments

1

i would suggest you do it this way

file=open('userlist.txt', 'r')
line=file.readlines()
users=[l.strip.split(':') for l in line]

what this does is that it takes a line, "uname":"pass", splits it with ":" which gives you ["uname","pass"] and it saves it in each index of the users array

you can now access username via [users[i][0]] and passwords via users[i][1]

Comments

0

As you described in your question, you want to add a new list [user, password] to an existing list of all users every time you loop over userlist.

You can do it this way:

    users = []
    with open('userlist.txt', 'r') as userlist:
        for line in userlist:
            user, pwd = line.strip().split(':')
            users.append([user, pwd])

But for this situation there's a better solution using dictionaries:

    users = {}
    with open('userlist.txt', 'r') as userlist:
        for line in userlist:
            user, pwd = line.strip().split(':')
            users[user] = pwd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.