0

The code below just print the first user from the outer loop and all the passwords from inner loop. Once the inner is executed once the program exit from the outer loop also.

passfile = open("passfile.txt", "r")
userfile = open("userfile.txt", "r")

for user in userfile:
    for password in passfile:
        print("user: " + user + "   password: " + password)
lunatic955
  • 31
  • 5

4 Answers4

3

Every iteration the inner loop is executed whatever is this. In this case it will read the file from the beginning till the end. Once it has reached the end of the file cannot read more no matter how many times the outer loop iterates.

If you can suppose that it contains user-password pairs you may try zip as suggested here.

Jónás Balázs
  • 781
  • 10
  • 24
2

I think this is the behaviour you actually want, see Jónás Balázs answer for the cause of problem:

Edited:

with open("passfile.txt", "r") as passfile:
    passwords = passfile.readlines()
with open("userfile.txt", "r") as userfile:
    usernames = userfile.readlines()

for user in usernames:
    for password in passwords:
        print("user:", user, "password:", password)
SimonF
  • 1,855
  • 10
  • 23
  • But this code is just going provide 1 to 1 relationship.. I want output something like this for eg: user1:password1 -- user1:password2 -- user1:password3 -- user2:password1 and so on – lunatic955 Jan 25 '19 at 07:31
1

Try to run both loops simultaneously:

userfile = open("userfile.txt", "r")
passfile = open("passfile.txt", "r")

for user, password in zip(userfile, passfile):
    print("user: " + user + "   password: " + password)
vipul petkar
  • 79
  • 1
  • 10
0

The problem you are encountering is as described by @Jónás Balázs. Use izip if using Python 2 or zip if python 3 so you can iterate over two files simultaneously in just a single loop.

try:
  from itertools import izip # For Python 2
except ImportError:
  izip = zip # For Python 3

for user, password in izip(open("userfile.txt"), open("passfile.txt")):
  print("User: " + user + "Password: " + password)

This is assuming that both files have the same number of lines and has a 1-to-1 relationship between the user and the password.

Whooper
  • 575
  • 4
  • 20