Bluecider
Bluecider

Reputation: 3

How to split into a 2-dimensional array python

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

Upvotes: 0

Views: 726

Answers (3)

Desiigner
Desiigner

Reputation: 2316

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

Upvotes: 0

Imtinan Azhar
Imtinan Azhar

Reputation: 1753

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]

Upvotes: 1

user2390182
user2390182

Reputation: 73450

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]

Upvotes: 1

Related Questions