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)
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.
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)
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)
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.
Related
I'm trying to write a Login Program in python. I'm trying to read and add the usernames, emails and passwords to a text file. When reading the file I'm using a class to create accounts using the usernames etc. and store them inside my users[] list so I can access it with something like "users[3].username". Everything worked fine but I'm having one problem: When printing the last value of each account (in this case the password) there is an additional empty line. I dont want this because I cant use it like that for example when checking if a password is correct.
This is the code
class Accounts:
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
users = []
def add_account(username, email, password):
file = open("useraccounts.txt", "a")
file.write(username + ", " + email + ", " + password + "\n")
file.close()
def read_accounts():
file = open("useraccounts.txt", "r")
count = 0
for line in file:
count += 1
file.seek(0)
for i in range(count):
x = file.readline()
x = x.rsplit(", ")
new_account = Accounts(x[0], x[1], x[2])
users.append(new_account)
file.close()
add_account("Banana", "banana#email.com", "1234")
read_accounts()
print(users[0].username)
print(users[0].email)
print(users[0].password)
print("Something")
This is what the Output looks like
Banana
banana#email.com
1234
Something
It also happens when dealing wiht multiple accounts and when writing the text file manually instead of using the add_account function.
I'm sure the problem is my read_accounts function, because the problem does not occur when creating an account manually like this
account = Accounts("Banana", "banana#email.com", "1234")
Also since this is one my firsts programs let me know if you have any other tips.
1 More thing: Originally my post started with "Hey guys" but it got removed. Why does that happen lol?
file.readline() doesn't strip the newline character from the end of the line, so when you split it up, the newline is still attached to the last element (the password). So you should add an rstrip() to your reading, e.g.:
x = file.readline().rstrip()
This should help, happy coding!
My program filters through a list of usernames and checks their availability on twitter. In testing I used a list that I entered manually into the code. However, once it was working I swapped them out for a txt file. Only to notice that actually it was no longer checking successfully for the first 4 names in the text file but was working for the last one.
I've printed the json output on the failed 4 tests and it was "Only use letters, numbers and '_'"
available = open("Available-Twitter.txt", "a")
with open ("accounts.txt", "r") as usernames:
for username in usernames:
r = requests.get("https://twitter.com/users/username_available?username={}".format(username))
print (r.json()['msg'])
print (' ')
if "!" in (r.json()['msg']):
print(Fore.GREEN + "Account available - {}".format(username))
available.write(username+"\n")
else:
print(Fore.RED + "Account is unavailable - {}".format(username))
The file generator produces lines that end with a newline character. You should strip it if you don't need it:
with open ("accounts.txt", "r") as usernames:
for username in usernames:
username = username.rstrip()
...
I am trying to create a Password Generator. The program is supposed to generate a List of random passwords and then write them to a .txt file. With the code below, the program is only writing the last password generated, rather than all of them.
#!/usr/bin/python3
import random
#The Characters List
Characters = "abcdefghijklmnopqrstuvwxyz!##$%^&*()_+-=[];'\,./ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
#Password Generator
#Get the Input form the User
Length = input("Password Length > ")
Length = int(Length)
#Get the Input form the User
PasswordNumber = input("Number of Passwords > ")
PasswordNumber = int(PasswordNumber)
for p in range(PasswordNumber):
Password = ""
for i in range(Length):
Password += random.choice(Characters)
print(Password)
f= open("PasswordList.txt","w+")
f.write(Password)
f.close()
My results:
Password Length > 10
Number of Passwords > 5
LgoQ$i%e_O
![i/NxsqQr
n-ydWA/9.5
ksI,jg]#8q
![xrU#=2##
But when I open the "PasswordList.txt" the text that is inside is only: ![xrU#=2##, the last password it generated.
Also I want the passwords to have the same format as seen on the terminal:
LgoQ$i%e_O
![i/NxsqQr
n-ydWA/9.5
ksI,jg]#8q
![xrU#=2##
and not like this:
LgoQ$i%e_O![i/NxsqQrn-ydWA/9.5ksI,jg]#8q![xrU#=2##
You get only one password because that's what you told it to do: generate and print out all the passwords. Once they're all generated, then you write only one password to the file.
You need to pull that print statement into your loop:
f = open("PasswordList.txt","w+")
for p in range(PasswordNumber):
Password = ""
for i in range(Length):
Password += random.choice(Characters)
print(Password)
f.write(Password + "\n")
f.close()
To get the same format, simply add a newline to each write, or use the writeln method.
Sample output, with 10 passwords of length 8:
w#wz+]S2
8t=G#r,F
H$aITs0&
=dMbird6
Y)Dpu]EZ
K\ZDNI*M
L6(2L_7_
VJL3GxF$
.nRt!XIa
=OXP8=aC
I am currently trying to learn Python. I know some basics and I'm trying to practise by making a game. My code so far is:
import time
import datetime
now = datetime.datetime.now()
name = input('What is your name? >> ')
file = open("users.txt","+w")
file.write(name + ' started playing at: ' + now.strftime("%Y-%m-%d %H:%M") + '. \n')
file.close()
account = input('Do you have an account ' + name + '? >> ')
while(account != 'yes'):
if(account == 'no'):
break
account = input('Sorry, I did not understand. Please input yes/no >> ')
if(account == 'yes'):
login = input('Login >>')
passwd = input('Password >>')
if login in open('accounts.txt').read():
if passwd in open('accounts.txt').read():
print('Login Successful ' + login + '!')
else:
print('Password incorrect! The password you typed in is ' + passwd + '.')
else:
print('Login incorrect! The login you typed in is ' + login + '.')
As you probably noticed I am working on a login system. Now please ignore all the bugs and inefficient code etc. I want to focus on how I can get Python to check for a line in a .txt file and, if it's there, check the one below.
My .txt file is:
loggn
pass
__________
I want to make the program multi-account. This is why I am using a .txt file. If you need me to clarify anything, please ask. Thankyou! :)
with open('filename') as f:
for line in f:
if line.startswith('something'):
firstline = line.strip() # strip() removes whitespace surrounding the line
secondline = next(f).strip() # f is an iterator, you can call the next object with next.
Store the results of "open('accounts.txt').read()" yourself, and iterate over them as an array - if you know what line number you are on, it is trivial to check the next. Assuming that every even numbered line is a login, and every odd numbered line is a password, you would have something like this:
success = False
# Storing the value in a variable keeps from reading the file twice
lines = open('account.txt').readlines()
# This removes the newlines at the end of each line
lines = [line.strip() for line in lines]
# Iterate through the number of lines
for idx in range(0, len(lines)):
# Skip password lines
if idx % 2 != 0:
continue
# Check login
if lines[idx] == login:
# Check password
if lines[idx + 1] == password:
success = True
break
if success:
print('Login success!')
else:
print('Login failure')
You may also consider changing your file format: using something that won't occur in the login name (such as a colon, unprintable ASCII character, tab, or similar) followed by the password for each line means you could use your original approach by just checking for (login + "\t" + password) for each line, rather than having to worry about having two lines.
I have been searching and mucking around for days trying to make a zip cracker in python 3.
I have a text file with my passwords in it called passwords.txt. and each password in on a new line. (no space in between lines)
e.g:
password
house
qwerty
the script runs ok and will extract the file in my zip. (zip password was qwerty). BUT if I rearrange my list like so:
password
qwerty
house
the script will not crack the zip. It will work fine with 'qwerty' as the only password in the list and will work if 'qwerty' is the last password in the list. To me its like the script is not terminating after using the correct password. I need a bit of a push in the right direction.
here is my (simple) code: (i'm no expert)
import zipfile
with open('passwords.txt') as passwordList:
myZip = zipfile.ZipFile('test.zip')
for line in passwordList:
try:
myZip.setpassword(pwd=line.encode())
myZip.extractall()
except:
pass
myZip.close()
any help will be appreciated.
Remove \n from your line variable with line.strip(b'\n') and not line.strip(), because password may have whitespace around itself.
Also you can pass pwd to extractall directly.
import zipfile
zip_file = zipfile.ZipFile('test.zip')
output_verbose = 2 # increase that for long password list
with open('passwords.txt', 'rb') as password_list:
for index, line in enumerate(password_list):
try:
pwd = line.strip(b'\n')
zip_file.extractall(pwd=pwd)
except RuntimeError:
if index % output_verbose == 0:
print('{}. The {} word not matched.'.format(index + 1, pwd))
else:
print('{}. Wow ! found the password: {}'.format(index + 1, pwd))
break
zip_file.close()
Demo:
1. The b'password' word not matched.
2. Wow ! found the password: b'qwerty'
justin = '''
+=======================================+
|..........Zip Cracker v 1.........|
+---------------------------------------+
|#Author: JUSTIN |
|#Contact: www.fb.com/rootx |
+=======================================+
|..........ZIP Cracker v 1.........|
+---------------------------------------+
'''
print justin
import zipfile
z1 = raw_input("Enter Your Zip File:")
z = zipfile.ZipFile(z1)
pf1=str(raw_input( "Enter password list: "))
pf=open(pf1,'r')
for x in pf.readlines():
password = x.strip('\n')
try:
z.extractall(pwd=password)
print "pass=" +password+ "\n"
exit(0)
except Exception,e:
pass