user2363217
user2363217

Reputation: 735

Split and strip output python

I am really having some issues with getting clean output from python after reading in a file.

Here is my code so far:

user_pass_list = []
count = 0
for Line in open(psw):
    fields = Line.strip("\n").strip(",").split(":")
    user_pass_list.append(fields)
    count = count + 1

print (count)

for item in range (0, count):
    print (user_pass_list[item])

Here is what I keep getting as output:

['administrator', 'admin']
['']
['administrator', 'password']
['']
['admin', '12345']
['']
['admin', '1234']
['']
['root', 'root']
['']
['root', 'password']
['']
['root', 'toor']

Here is the text file that I am trying to read in to a list.

administrator:admin    
administrator:password    
admin:12345    
admin:1234    
root:root    
root:password    
root:toor

Could someone please help me? What I want is for each field to have its own list.

users[0]="administrator"
passwords[0]="admin"
users[1]="administrator"
passwords[1]="password"

Any suggestions?

Upvotes: 1

Views: 2014

Answers (3)

thebjorn
thebjorn

Reputation: 27360

There are a number of different ways to do this...

The straight forward way:

up0 = []
with open('pwd.txt') as fp:
    for line in fp:
        words = line.split(':')
        username, password = [w.strip() for w in words]
        up0.append((username, password))

using a nested list comprehension:

up1 = [(username, password.strip())
       for (username, password)
       in [line.split(':') for line in open('pwd.txt').readlines()]]

if you're using Python 2.7 that could be written with a simple map:

up2 = [map(str.strip, line.split(':')) for line in open('pwd.txt').readlines()]

Python 3 requires that you wrap the map inside list(), or you could replace the map by a list comprehension:

up3 = [[w.strip() for w in line.split(':')] for line in open('pwd.txt').readlines()]

and finally for those times when you feel funky, regular expressions:

import re
up4 = re.findall(r'([^:]+):([^\s]+).*\n', open('pwd.txt').read())

there seems like there should be a solution using itertools too... ;-)

You can print them all out by e.g. (Python 2.7):

print "Count:", len(up0)

for item in up0:
    print item

or (Python 3):

print("Count:", len(up0))

for username, password in up0:
    print("username={}, password={}".format(username, password)

I would suggest using the up0 version if you want a recommendation..

[update]: just saw you wanted all the usernames in one array and the passwords in another...

The above code creates a list of tuples, as you can see by e.g. using pprint:

import pprint
pprint.pprint(up0)

gives

[('administrator', 'admin'),
 ('administrator', 'password'),
 ('admin', '12345'),
 ('admin', '1234'),
 ('root', 'root'),
 ('root', 'password'),
 ('root', 'toor')]

this can be easily converted to what you want by:

username, password = zip(*up0)
print 'username:', username
print 'password:', password

which gives

username: ('administrator', 'administrator', 'admin', 'admin', 'root', 'root', 'root')
password: ('admin', 'password', '12345', '1234', 'root', 'password', 'toor')

Upvotes: 0

Gary Fixler
Gary Fixler

Reputation: 6048

How about instead of fields you try to unpack it into two vars immediately, and wrap it in a try/except so if it doesn't unpack to exactly two fields, it simply fails and skips it?

for Line in open(psw):
    try:
        user, pswd = Line.strip("\n").strip(",").split(":")
        user_pass_list.append([user, pswd])
        count = count + 1
    except:
        pass

You might also want to strip spaces and tabs.

Upvotes: 1

PepperoniPizza
PepperoniPizza

Reputation: 9112

You could use 2 lists, users and passwords like this:

users = []
passwords = []

with open(psw, 'rb') as fin:
    for line in fin.readlines():
        fields = line.strip().split(':')
        users.append(fields[0])
        passwords.append(fields[1])

But I think it would be more useful to have a list of tuples:

credentials = []

with open(psw, 'rb') as fin:
    for line in fin.readlines():
        fields = line.strip().split(':')
        credentials.append((fields[0], field[1]))

Upvotes: 1

Related Questions