Make a mix of 2 Files Python - python

Hey I am currently making a little tool just for fun. Its suposed to take a username and a password list and print out all combinations possible.
Python 2.7
My code
while True:
cnt = 1
cntpw = 1
currentusernameopen = open((usernamelist), "r")
linesim = currentusernameopen.read().split("\n")
usernameused = (linesim[cnt])
while True:
try:
currentpassopen = open((passwordlist), "r")
linesimpw = currentpassopen.read().split("\n")
pwused = (linesimpw[cntpw])
print usernameused+":"+pwused
cntpw += 1
except:
cnt += 1
But when it reaches the end of passowrds it just prints:
USER1:
and stops

You shouldn't use exceptions to control "normal" flow of program
You should use meaningful names for your variables, and use underscores to separate words
You can just iterate on file, no need to read all and then split
And there is no need to keep counters like that
EDIT: my proposal for such exercise:
#!/usr/bin/env python3
users = open("users", "r")
passwords = open("passwords", "r")
for user in users:
for password in passwords:
print("%s: %s" % (user.strip(), password.strip()))
passwords.seek(0)
strip removes all trailing whitespaces, here for last "\n"

Related

Python class adds empty line to last value

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!

Combine lines when writing to file in Python?

So I'm trying to write all this info to a .txt file, but due to the names being pulled from a .txt file that goes
Liam
Noah
William
etc...
When I write to a file, it puts the first and last names on separate lines from everything else.
I've looked on StackOverflow for a solution but I couldn't find anything specific enough.
password = input('Enter the Password you would like to use ')
open('names.txt', 'r+')
lines = open("names.txt").readlines()
firstName = lines[0]
words = firstName.split()
firstNameChoice = random.choice(lines)
open('names.txt', 'r+')
lines = open("names.txt").readlines()
lastName = lines[0]
words = lastName.split()
lastNameChoice = random.choice(lines)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(firstNameChoice)
accountFile.write(lastNameChoice)
accountFile.write(randomNumber)
accountFile.write('#')
accountFile.write(catchall)
accountFile.write(':')
accountFile.write(password)
accountFile.write('\n')
signUp()
Expectation would be everything printed to one line but that's not the case.
As a quick fix for your problem, you could merge all writing commands in one line:
with open('accounts.txt', 'a') as accountFile: # using a context manager is highly recommended
# with spaces
accountFile.write('{} {} {} # {} : {} \n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
# without spaces
accountFile.write('{}{}{}#{}:{}\n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
If my understanding is right then you want to write everything in one line.
The variables you are writing containing \n while writing into the file.
So you have to replace it with a ' '. Replace this code into your program like:
accountFile.write(firstNameChoice.replace('\n',' '))
accountFile.write(lastNameChoice.replace('\n',' '))
accountFile.write(str(randomNumber).replace('\n',' '))
accountFile.write('#'.replace('\n',' '))
#accountFile.write(catchall)
accountFile.write(':'.replace('\n',' '))
accountFile.write(str(password).replace('\n',' '))
Now it will print like this WilliamWilliam448#:dsada
By the way I dont know what you mean by catchall
The reason it puts it all on a new line is because the strings of your names contains the "\n" on the end because it has an enter to a new line. There is an easy fix for this.
Where you define your first and last name variables add .rstrip() at the end. Like this:
firstNameChoice = random.choice(lines).rstrip()
lastNameChoice = random.choice(lines).rstrip()
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(f'{firstNameChoice} {lastNameChoice} {randomNumber} # {catchall}: {password} \n')

How do I split a combo list in a large text file?

my problem is that I have a very large database of emails and passwords and I need to send it to a mysql database.
The .txt file format is something like this:
emailnumberone#gmail.com:password1
emailnumbertwo#gmail.com:password2
emailnumberthree#gmail.com:password3
emailnumberfour#gmail.com:password4
emailnumberfive#gmail.com:password5
My idea is to make a loop that takes the line and make it a variable, search the ":" and pick the text before, send it to the db and then the same with the after part of the line. How do I do this?
Short program with some error handling:
Create demo data file:
t = """
emailnumberone#gmail.com:password1
emailnumbertwo#gmail.com:password2
emailnumberthree#gmail.com:password3
emailnumberfour#gmail.com:password4
emailnumberfive#gmail.com:password5
k
: """
with open("f.txt","w") as f: f.write(t)
Parse data / store:
def store_in_db(email,pw):
# replace with db access code
# see http://bobby-tables.com/python
# for parametrized db code in python (or the API of your choice)
print("stored: ", email, pw)
with open("f.txt") as r:
for line in r:
if line.strip(): # weed out empty lines
try:
email, pw = line.split(":",1) # even if : in pw: only split at 1st :
if email.strip() and pw.strip(): # only if both filled
store_in_db(email,pw)
else:
raise ValueError("Something is empty: '"+line+"'")
except Exception as ex:
print("Error: ", line, ex)
Output:
stored: emailnumberone#gmail.com password1
stored: emailnumbertwo#gmail.com password2
stored: emailnumberthree#gmail.com password3
stored: emailnumberfour#gmail.com password4
stored: emailnumberfive#gmail.com password5
Error: k
not enough values to unpack (expected 2, got 1)
Error: : Something is empty: ': '
Edit: According to What characters are allowed in an email address? - a ':' may be part of the first part of an email if quoted.
This would theoretically allow inputs as
`"Cool:Emailadress#google.com:coolish_password"`
which will get errors with this code. See Talip Tolga Sans answer for how to break down the splitting differently to avoid this problem.
This can be done through simple split() method of the strings in python.
>>> a = 'emailnumberone#gmail.com:password1'
>>> b = a.split(':')
>>> b
['emailnumberone#gmail.com', 'password1']
To accomodate #PatrickArtner's complex password fail this can be done:
atLocation = a.find('#')
realSeperator = atLocation + a[atLocation:].find(':')
emailName = a[0:atLocation]
emailDomain = a[atLocation:realSeperator]
email = emailName + emailDomain
password = a[realSeperator + 1:]
print(email, password)
>>> emailnumberone#gmail.com com:plex:PassWord:fail
str.find() returns the first occurrence location of the given character in the given string. Emails can have : in their name field but they can not have #. So first locating the # then locating the : would give you the correct separation locations. After that splitting the string will be piece of cake.
Open file as context manager (with open(...)), You can iterate over the lines with a for loop, then regex match(re Module)(or just split on ":") and use sqlite3 to insert your values to DB.
So the file:
with open("file.txt", "r") as f:
for line in f:
pass #manipulation
Sqlite3 Docs: https://docs.python.org/2/library/sqlite3.html

replace function not working with list items

I am trying to use the replace function to take items from a list and replace the fields below with their corresponding values, but no matter what I do, it only seems to work when it reaches the end of the range (on it's last possible value of i, it successfully replaces a substring, but before that it does not)
for i in range(len(fieldNameList)):
foo = fieldNameList[i]
bar = fieldValueList[i]
msg = msg.replace(foo, bar)
print msg
This is what I get after running that code
<<name>> <<color>> <<age>>
<<name>> <<color>> <<age>>
<<name>> <<color>> 18
I've been stuck on this for way too long. Any advice would be greatly appreciated. Thanks :)
Full code:
def writeDocument():
msgFile = raw_input("Name of file you would like to create or write to?: ")
msgFile = open(msgFile, 'w+')
msg = raw_input("\nType your message here. Indicate replaceable fields by surrounding them with \'<<>>\' Do not use spaces inside your fieldnames.\n\nYou can also create your fieldname list here. Write your first fieldname surrounded by <<>> followed by the value you'd like to assign, then repeat, separating everything by one space. Example: \"<<name>> ryan <<color>> blue\"\n\n")
msg = msg.replace(' ', '\n')
msgFile.write(msg)
msgFile.close()
print "\nDocument written successfully.\n"
def fillDocument():
msgFile = raw_input("Name of file containing the message you'd like to fill?: ")
fieldFile = raw_input("Name of file containing the fieldname list?: ")
msgFile = open(msgFile, 'r+')
fieldFile = open(fieldFile, 'r')
fieldNameList = []
fieldValueList = []
fieldLine = fieldFile.readline()
while fieldLine != '':
fieldNameList.append(fieldLine)
fieldLine = fieldFile.readline()
fieldValueList.append(fieldLine)
fieldLine = fieldFile.readline()
print fieldNameList[0]
print fieldValueList[0]
print fieldNameList[1]
print fieldValueList[1]
msg = msgFile.readline()
for i in range(len(fieldNameList)):
foo = fieldNameList[i]
bar = fieldValueList[i]
msg = msg.replace(foo, bar)
print msg
msgFile.close()
fieldFile.close()
###Program Starts#####--------------------
while True==True:
objective = input("What would you like to do?\n1. Create a new document\n2. Fill in a document with fieldnames\n")
if objective == 1:
writeDocument()
elif objective == 2:
fillDocument()
else:
print "That's not a valid choice."
Message file:
<<name>> <<color>> <<age>>
Fieldname file:
<<name>>
ryan
<<color>>
blue
<<age>>
18
Cause:
This is because all lines except the last line read from the "Fieldname" file contains "\n" characters. So when the program comes to the replacing part fieldNameList , fieldValueList and msg looks like this:
fieldNameList = ['<<name>>\n', '<<color>>\n', '<<age>>\n']
fieldValueList = ['ryan\n', 'blue\n', '18']
msg = '<<name>> <<color>> <<age>>\n'
so the replace() function actually searches for '<<name>>\n','<<color>>\n','<<age>>\n' in msg string and only <<age>> field get replaced.(You must have a "\n" at the end of msg file, otherwise it won't be replaced as well).
Solution:
use rstrip() method when reading lines to strip the newline character at the end.
fieldLine = fieldFile.readline().rstrip()

Python- Saving Results to a File and Recalling Them

I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.
The program gives the user the ability to remove, add, or find a student. Here is the code:
students={}
def add_student():
#Lastname, Firstname
name=raw_input("Enter Student's Name")
#ID Number
idnum=raw_input("Enter Student's ID Number")
#D.O.B.
bday=raw_input("Enter Student's Date of Birth")
students[idnum]={'name':name, 'bday':bday}
def delete_student():
idnum=raw_input("delete which student:")
del students[idnum]
def find_student():
print "Find"
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
add_student()
elif selection == '2':
delete_student()
elif selection == '3':
find_students
elif selection == '4':
break
else:
print "Unknown Option Selected!"
The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.
I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:
f = open("myfile.txt", "a")
I'm new to Python so any help would be appreciated. Thanks so much.
It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:
with open('nameOfYourSaveFile', 'w') as saveFile:
#.write() does not automatically add a newline, like print does
saveFile.write(myString + "\n")
Here's an answer that explains the different arguments to open, as in w, w+, a, etc.
As an example, say we have:
with open('nameOfYourSaveFile', 'w') as saveFile:
for i in xrange(10):
saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")
To read the file back, we do:
names = []
numbers = []
emails = []
with open('nameOfYourSaveFile', 'r') as inFile:
for line in inFile:
#get rid of EOL
line = line.rstrip()
#random example
names.append(line[0])
numbers.append(line[1])
emails.append(line[2])
#Or another approach if we want to simply print each token on a newline
for word in line:
print word
import pickle,os
if os.path.exists("database.dat"):
students = pickle.load(open("database.dat"))
else:
students = {}
... #your program
def save():
pickle.dump(students,open("database.dat","w"))

Categories