简体   繁体   中英

Parsing a text file with Python and split()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM