Reputation: 57
In my python class I have created a nested for loop, the script and the output should be pretty straight forward. What is not straight forward is how do I fix this!!
I have googled for hours looking at examples of other nested for loops, but have not found any similar to mine to help me understand this problem.
Here is the entire script:
LIST = "list.txt"
USERNAME = "users.txt"
# Open the files to read from
listtxt = open(LIST,"r")
userstxt = open(USERNAME,"r")
# For each user in users.txt
for USER in userstxt:
print ("Started new user %s" % USER)
for PASSWD in listtxt:
print USER + ", " + PASSWD
OUTPUT
Started new user user1
user1
, pass1
user1
, pass2
user1
, pass3
user1
, pass4
user1
, pass5
Started new user user2
Started new user user3
Started new user user4
Started new user user5
Do you see the problem already? The problem is it iterates thru the first user correctly, but on all subsequent users it only goes thru the first (user) loop but does not execute the password loop
Upvotes: 2
Views: 524
Reputation: 77847
I tried your code as given, and it works fine for me:
Started new user user1
user1, pass1
user1, pass2
user1, pass3
user1, pass4
user1, pass5
Started new user user2
user2, pass1
user2, pass2
user2, pass3
user2, pass4
user2, pass5
Started new user user3
...
It looks like something has fouled your loop nesting syntax. This makes me suspect your indentation. Have you mixed tabs and spaces? Are there non-printing characters in between?
I recommend that you highlight each line's leading whitespace (blank stuff up to the first character) and retype it as all spaces.
You might also try the brute-force approach: insert a strategic print statement or two, showing the loop index at that point. This can help trace the loop's logic, although the prints you already have do this pretty well.
Upvotes: 0
Reputation: 12012
You're exhausting the file on the first iteration of the outer loop. You should probably read the list.txt
file into a list, then loop over that list. You also probably want to strip the newlines off of the lines before using them.
users_filepath = 'users.txt'
passwords_filepath = 'list.txt'
with open(users_filepath, 'r') as users_file:
users = [line.strip() for line in users_file]
with open(passwords_filepath, 'r') as password_file:
passwords = [line.strip() for line in password_file]
for user in users:
print "Started new user {user}".format(user=user)
for password in passwords:
print "{user}, {password}".format(user=user, password=password)
Upvotes: 4