-5

I have two text files "usernames.txt" and "passwords.txt" and I want to have them print out in a specific order, I have a snippet of code that does exactly what I need but I feel like It can be shortened.

with open('passwords.txt','r') as f:
    for line in f:
        for password in line.split():
            with open('usernames.txt','r') as f:
                for line in f:
                    for username in line.split():
                        print username +":"+ password

This works perfect for me what I feel like I can make it even shorter!

current output is this:

username1:password
username1:password1
username1:password2
username2:password
username2:password1
username2:password2
niro
  • 63
  • 2

2 Answers2

3

Don't worry about making it shorter, make it more readable by removing nesting.

  1. Open both files in one line
  2. Extract the data with a nested list comprehension
  3. Use itertools.product to get your combinations

Something like this

    import itertools

    with open('passwords.txt', 'r') as pf, open('usernames.txt', 'r') as uf:
        passwords = [pwd for line in pf for pwd in line.split()]
        usernames = [uname for line in uf for uname in line.split()]

    for username, password in itertools.product(usernames, passwords):
        print("{}: {}".format(username, password)
Community
  • 1
  • 1
Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46
  • Use `itertools.chain.from_iterable(map(operator.methodcaller("split"), pf))` and so as for `uf`. Then use it for the `itertools.product` **inside** the with statement. Will be WAY more efficient, and consume less memory. – Bharel Sep 23 '16 at 23:24
-1

Not much shorter (5 vs 7 lines) but at least a bit more readable, if I say so myself:

passwords = open('passwords.txt').readlines()
usernames = open('usernames.txt').readlines()

for p in passwords:
    for u in usernames:
        print '%s:%s' % (u.strip(), p.strip())

Edit

This answer assumes your passwords.txt and usernames.txt have one entry per line. Not a single line with multiple entries.

Jasper
  • 114
  • 9
  • I don't think that's correct. The OP uses `split()` (which returns an list) and not `.strip()` (which returns a string). – MSeifert Sep 23 '16 at 23:08
  • The output of my version is the same as OP's, though. Without examples of his source files I can only make assumptions. My assumption was that the files would contain one entry per line. – Jasper Sep 23 '16 at 23:13
  • 1
    I realize you're quite a new member so please have a look at [How to answer (help center)](http://stackoverflow.com/help/how-to-answer). I think the general guideline is that if you don't know why/what the OP is doing then you should ask for clarification (comments) and **not** make assumptions. – MSeifert Sep 23 '16 at 23:20