2

I'm sure there's an easy answer to this, I just can't seem to figure out what's the best solution.

I have a text file that contains the following: a username and a password. An example is below:

mcgoga12,password
shelby12,password1

I want to open this file, and read in the file. However, I want to store the username (mcgoga12, etc...) and the password (password, etc...) in two separate lists.

Does anyone have a specific suggestion as to how to parse this?

Here's what I've tried:

with open("credentials.txt", "r") as infile:
    users = infile.read().rsplit(',',3)
    print users

However, I keep getting this output (clearly its not separating it)

['mcgoga12', 'password\nshelby12', 'password1\n']

1 Answer 1

2

The new lines are there in the file, which have to be explicitly removed with strip family of functions. We use rstrip and then we split the line based on , which will give us a list which has username and its corresponding password. Now, we do this for all the lines and finally transform the data with zip function, like this

with open("credentials.txt", "r") as infile:
    data = [line.rstrip().split(",") for line in infile]
    usernames, passwords = zip(*data)
    print usernames, passwords
    # ('mcgoga12', 'shelby12') ('password', 'password1')

If we print just the data, it would look something like this

[['mcgoga12', 'password'], ['shelby12', 'password1']]

and when we zip it with unpacking, it will become

('mcgoga12', 'shelby12') ('password', 'password1')

when we say zipping with unpacking, it means that we are unpacking the sequence as parameters to the function. For example,

zip(*data)

is just a shorthand notation for

zip(data[0], data[1]...)
Sign up to request clarification or add additional context in comments.

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.