I hope the title wasn't too confusing, but you'll see what I meant by that in a bit. In the meantime, some backstory-- I'm working on a function that generates random usernames and passwords and writes them in a text file as username:password for another program that collects the username:password line as:
string = line.split(":")
username = string[0]
pwd = string[1]
Why does this matter? Well, when I run my function:
Code:
# To generate users and passwords for the password file:
"""
Usage: count-- how many accounts to generate
file-- where to dump the accounts
method-- dict is where it loops through words
and chooses random ones as users and passwords,
and brute (not implemented yet) is where it chooses
random characters and strings them together as users
and passwords.
users-- if you want any filled in users, put them in here.
passes-- if you want any filled in passes, put them in here.
"""
def genAccts(count, file, method="dict", users=[], passes=[]):
try:
f = open(file, "w")
if method == "dict":
dictionary = "Dictionary.txt"#input("[*] Dictionary file: ")
d = open(dictionary, "r")
words = d.readlines()
d.close()
accts = []
for b in range(0, count):
global user
global pwd
user = random.choice(words)
pwd = random.choice(words)
if b < len(users)-1:
user = users[b]
if b < len(passes)-1:
pwd = passes[b]
acct = [user, pwd]
accts.append(acct)
print("[+] Successfully generated",count,"accounts")
for acct in accts:
combined = acct[0]+":"+acct[1]
print(combined)
f.write(combined)
f.close()
print("[+] Successfully wrote",count,"accounts in",file+"!")
except Exception as error:
return str(error)
genAccts(50, "brute.txt")
In my password file brute.txt, I get an output like
quainter
:slightest
litany
:purples
reciprocal
:already
delicate
:four
and so I'm wondering why is a \n added after the username?
You can fix this by replacing:
words = d.readlines()
with:
words = [x.strip() for x in d.readlines()]
words = d.readlines()
The above function returns a list which contains each line as an item. Every word will contain \n character at the end. So to get the required output, you have to trim the white space characters for username.
user = random.choice(words).strip()
Above line will solve your issue!
Use this:
def genAccts(count, file, method="dict", users=[], passes=[]):
try:
f = open(file, "w")
if method == "dict":
dictionary = "Dictionary.txt"#input("[*] Dictionary file: ")
d = open(dictionary, "r")
words = d.readlines().strip()
d.close()
accts = []
for b in range(0, count):
global user
global pwd
user = random.choice(words)
pwd = random.choice(words)
if b < len(users)-1:
user = users[b]
if b < len(passes)-1:
pwd = passes[b]
acct = [user, pwd]
accts.append(acct)
print("[+] Successfully generated",count,"accounts")
for acct in accts:
combined = acct[0]+":"+acct[1]
print(combined)
f.write(combined)
f.close()
print("[+] Successfully wrote",count,"accounts in",file+"!")
except Exception as error:
return str(error)
genAccts(50, "brute.txt")
Related
I have an issue where when I append to a file, a newline is always added for some reason. This breaks my code. It is meant to be some sort of login system. I have searched for answers alot. Currently I have found the .rstrip('\r'), .strip('\t') and .strip('\n') have not worked.
Example:
I write to a file like this when it already has the contents password1,username1<>:
print("Create")
with open('database.txt', 'a') as database:
username = input("Enter a username: ")
password = input("Enter a password: ")
combined = (password + "," + username + "<>")
combined = combined.strip('\n')
combined = combined.strip('')
combined = combined.strip(' ')
combined = combined.rstrip('\r')
combined = combined.strip('\t')
database.write(combined)
database.close()
#checking total number of users
with open('usernum.txt', 'r+') as usernum:
#the current number + 1 will be the number of the new user
total_num_of_users = usernum.read()
total_num_of_users = int(total_num_of_users) + 1
#incrementing for future numbers
total_num_of_users = str(total_num_of_users)
usernum.truncate(0)
usernum.write(total_num_of_users)
usernum.close()
#making a file containing the users place/number
namefile = str(username) + '.txt'
with open(namefile, 'w+') as usernum:
usernum.write(total_num_of_users)
usernum.close()
Please ignore the fact that the file is called database.txt lol. If my input is username2 and password2 my expected output is:
password1,username1<>password2,username2<>
However instead I get:
password1,username1<>
password2,username2<>
Can anyone help me wth this? Thanks in advance
file=open('New Text Document.txt','w')
lines=file.writelines(['username:ds_jr\n','password:89120&%'])
file.close()
file=open('New Text Document.txt','r')
file.readlines()
username=input('username:')
password=input('password:')
check=['username:'+username+'\n','password:'+password]
if check == lines:
print('hello ds_jr , welcome!')
else:
print('not found')
How to compare input username and password against .txt file content.
file=open('New Text Document.txt','w')
lines=file.writelines(['username:ds_jr\n','password:89120&%'])
file.close()
username=input('username:')
password=input('password:')
file = open('New Text Document.txt')
check = file.read()
if username and password in check:
print('hello ds_jr , welcome!')
else:
print('not found')
Lookups in Python are best implemented in dictionaries. Dictionaries can also be useful for holding the information that you want to write into the file. In this case there are only two values but for flexibility let's put those into a dictionary to begin with.
Choose a format for the file that can be understood later when reading.
When the file is read, build a new dictionary to store the keywords and values.
Now you can get the user input and check the values entered against the new dictionary.
FILE = 'New Text Document.txt'
USERNAME = 'username'
PASSWORD = 'password'
out_d = {USERNAME: 'ds_jr', PASSWORD: '89120&%'}
with open(FILE, 'w') as f:
for k, v in out_d.items():
print(f'{k}={v}', file=f)
in_d = dict()
with open(FILE) as f:
for line in map(str.strip, f):
if (eq := line.find('=')) >= 0:
in_d[line[:eq]] = line[eq+1:]
username = input(f'{USERNAME}: ')
password = input(f'{PASSWORD}: ')
if username == in_d.get(USERNAME) and password == in_d.get(PASSWORD):
print("You're good to go")
else:
print('Incorrect username or password')
Now let's say that you want to keep more information in the file. All you have to do is edit the in_d dictionary appropriately with no need to make any other modifications to the code
points = "temp"
a = "temp"
f = "temp"
def pointincrementer():
global points
points = 0
for line in f:
for word in a:
if word in line:
scorelen = int(len(user+","))
scoreval = line[0:scorelen]
isolatedscore = line.replace(scoreval,'')
if "," in line:
scorestr = isolatedscore.replace(",","")
score = int(scorestr)
points = score + 1
print(points)
def score2():
f = open('test.txt','r')
a = [user]
lst = []
for line in f:
for word in a:
if word in line:
pointincrementer()
print(points)
point = str(points)
winning = (user+","+point+","+"\n")
line = line.replace(line,winning)
lst.append(line)
f.close()
f = open('test.txt','w')
for line in lst:
f.write(line)
f.close()
print("Points updated")
user = input("Enter username: ") #change so user = winners userid
with open('test.txt') as myfile:
if user in myfile.read():
score2()
else:
f = open('test.txt','r')
f2 = f.read()
f3 = (f2+"\n"+user)
f.close()
f = open('test.txt','w')
f.write(f3)
f.close()
score2()
This is paired with test.txt, which looks like this:
one,1,
two,5,
three,4,
four,94,
When this code is run, it it will ask the user their name (as expected) and then will print 0 (when it should instead print the user's score) and then Points updated. Anybody know how to sort this out?
There are many problems with your code. You should not be using global variables like that. Each function should be passed what it needs, do its computing, and return values for the caller to handle. You should not be reading the file multiple times. And you can't write the file while you still have it open with the with statement.
Here, I read the file at the beginning into a Python dictionary. The code just updates the dictionary, then writes it back out at the end. This makes for a simpler and more maintainable structure.
def readdata(fn):
data = {}
for row in open(fn):
info = row.strip().split(',')
data[info[0]] = int(info[1])
return data
def writedata(fn,data):
f = open(fn,'w')
for k,v in data.items():
print( f"{k},{v}", file=f )
def pointincrementer(data,user):
return data[user] + 1
def score2(data, user):
points = pointincrementer(data, user)
print(points)
data[user] = points
print("Points updated")
user = input("Enter username: ")
data = readdata( 'test.txt' )
if user not in data:
data[user] = 0
score2(data, user)
writedata( 'test.txt', data )
The f in pointincrementer() refers to the "temp" string declared on the third line. The f in score2() refers to the file handle declared immediately below the function header. To get around this, you can pass the file handle into pointincrementer():
def pointincrementer(file_handle):
global points
points = 0
for line in file_handle:
for word in a:
if word in line:
scorelen = int(len(user+","))
scoreval = line[0:scorelen]
isolatedscore = line.replace(scoreval,'')
if "," in line:
scorestr = isolatedscore.replace(",","")
score = int(scorestr)
points = score + 1
print(points)
def score2():
file_handle = open('test.txt','r')
a = [user]
lst = []
for line in f:
print(line)
for word in a:
if word in line:
pointincrementer(file_handle)
print(points)
point = str(points)
winning = (user+","+point+","+"\n")
line = line.replace(line,winning)
lst.append(line)
f.close()
f = open('test.txt','w')
for line in lst:
f.write(line)
f.close()
print("Points updated")
This leads to a parsing error. However, as you haven't described what each function is supposed to do, this is the limit to which I can help. (The code is also extremely difficult to read -- the lack of readability in this code snippet is likely what caused this issue.)
i have made two lists from a database. one list for emails and another for passwords. i am trying to write the lists to a file using. using the following code but only the last items of the lists are getting written to the file
from app import db
from app import Users
filtered_users = []
all_users = Users.query.all()
filtered_users = all_users.copy()
# print(filtered_users)
for user in filtered_users:
`filtered_emails = []`
`filtered_passwords = []`
`filtered_emails.append(user.email)`
`filtered_passwords.append(user.password)`
`# print(filtered_emails, filtered_passwords)`
with open("users.txt", "w") as f:
`for email in filtered_emails:`
`for password in filtered_passwords:`
`#print(email, password)`
`print(email, password, file=f)`
Your loop resets filtered_emails and filtered_passwords on each iteration. You should at least remove that. And at write time you use nested loops (each email against each password) while emails and passwords should be bound.
You should do:
filtered_users = []
all_users = Users.query.all()
filtered_users = all_users.copy()
# print(filtered_users)
for user in filtered_users:
filtered_emails.append(user.email)
filtered_passwords.append(user.password)
# print(filtered_emails, filtered_passwords)
with open("users.txt", "w") as f:
for i, email in enumerate(filtered_emails):
#print(email, password)
print(email, filtered_passwords[i], file=f)
But it would be simpler to write to the file directly:
filtered_users = []
all_users = Users.query.all()
filtered_users = all_users.copy()
# print(filtered_users)
with open("users.txt", "w") as f:
for user in filtered_users:
print(user.email, user.password, file=f)
you can try use 'a' instead of 'w',because of the way of 'w' will delete all information and write from the first line。
filtered_emails = ['xx#xx.com','yyy#yy.com','zzz#zz.com']
filtered_passwords = ['1','2','345']
with open("users.txt", "w") as f:
for item in zip(filtered_emails,filtered_passwords):
f.write(item[0]+' ')
f.write(item[1]+'\n')
Assuming all of the entries are strings.zip returs a tuple of username and passwords.you can use itertools.izip_longest if you want to deal with lists of unequal length
Output:
xx#xx.com 1
yyy#yy.com 2
zzz#zz.com 345
I'm making a script that fills a text document with responses from an api. The api is being asked to convert usernames from a list to universally unique identifiers. I keep getting this error and can't find a way around it. "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
Sample of accounts.txt
knapplace
Coppinator
tynow
Pman59
ButterMusty
FlyHighGuy13
Seyashi
fluzzygirl1
SquidMan55
leonrules9
BarthGimble
MTR_30
Darkshadow402
Deathmyster
Team_Everlook
Sheathok
KCFrost
mendog
Allfaal117
theLP25D
Zimyx
Blurrnis
redboy678
moose_breeder
kaser12345
import requests
import json
file1 = open('accounts.txt', 'r')
usernames = []
for line in file1:
stripped_line = line.strip()
usernames.append(stripped_line)
file1.close()
for x in usernames:
username = str(x)
url = ("https://api.mojang.com/users/profiles/minecraft/"+username+"?at=1462770000")
y = requests.get(url)
y_data = y.json()
uuid = y_data['id']
uuids = []
uuids.append(uuid)
file2 = open('uuids.txt', 'w')
file2.writelines(uuids)
file2.close()
file2 = open('uuids.txt', 'r')
lines = file2.readlines()
Note: #Ali makes a great point about checking for an empty reply. With that fix it works like a champ for me with a few other minor changes:
Used usernames provided by OP instead of reading them in from a file.
Moved initialization of uuids out of for loop to avoid it being reset for each username.
Modfied file i/o stuff to what I am more used to working with. ;^)
import requests
import json
usernames = [
"knapplace",
"Coppinator",
"tynow",
]
uuids = []
for x in usernames:
username = str(x)
url = ("https://api.mojang.com/users/profiles/minecraft/"+username+"?at=1462770000")
y = requests.get(url)
if len(y.content) == 0:
continue # Skip processing this username
y_data = y.json()
uuid = y_data['id']
uuids.append(uuid)
with open('uuids.txt', 'w') as f:
for uuid in uuids:
f.write(uuid + '\n')
with open('uuids.txt', 'r') as f:
read_data = f.read()
print(read_data)
Output:
c9998bafea3146d5935f4e215b6b4351
5c321f81409847a0907c4b30c342217f
9f206def69bf407fbab6de7c9b70ff80
I checked the URL you pasted. If the user does not exist, the API does not return any content but still returns a successful status. That is what the error means — it expected there to be a JSON object starting at char 0.
Essentially, you need to handle the case when the response is empty before you try to execute a y.json() by checking y.content. If y.content is empty, skip processing the current username and go to the next one.
y = requests.get(url)
if len(y.content) == 0:
continue # Skip processing this username
# The rest of the code only runs if y.content is not empty.
y_data = y.json()
uuid = y_data['id']