1

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?

3
  • You don't want a list you want a dictionary. Commented Jun 22, 2014 at 21:58
  • I didn't see your count print out.. I don't think it's going to be the value you expect it to be. Commented Jun 22, 2014 at 21:58
  • You also didn't define, nor attempt to populate a users or passwords list variables. Commented Jun 22, 2014 at 22:00

3 Answers 3

1

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]))
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting an error TypeError: Type str doesn't support the buffer API. I am trying the method you suggested with tuples.
1

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.

5 Comments

There are no commas in the input, you have used the keyword pass as a variable name and no closing of the file. How this got upvoted I don't know.
Thanks. Fixed the pass var name (been working in Clojure and Haskell lately - slipping a bit in Python!). The comma strip came from the OP's OP.
I think the comma comes from the OP not really knowing what he/she is doing, might be worth adding that using with is usually the way to go when opening files.
It's a good point, but I just wanted to answer the asked question without transforming all of their code out from under them. I'd change other things, too, if it were my code (e.g. I'd probably use a dict).
I'd add a note about with and the commas in a comment to the OP.
0

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

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.