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
Related
I am trying to make a username and password that gets taken from a text file. The username and password is added at the beginning and used after. I add a username and password at the start and it works. It adds it to the text document but it says that it isn't on the document when i enter the 2 previously created credentials. I put the part i belive is giving issues in **. Any way to make this work properly? If my point isn't clear i can specify more if necessary. Thanks.
import time
import sys
text1 = input("\n Write username ")
text2 = input("\n Write password ")
saveFile = open('usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
uap = saveFile.read()
saveFile.close()
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
*if username in uap and password in uap:
print("Access Granted")*
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
saveFile.write writes to the end of the file, so the file cursor points to the end of the file.
saveFile.read() reads from the current position to the end (docs).
You need to move the file cursor to the beginning of the file, before reading:
text1 = 'foo'
text2 = 'bar'
saveFile = open('/tmp/usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
saveFile.seek(0)
uap = saveFile.read()
print(uap)
Out:
foo
bar
This is a simple program that prompts for the length of passwords, and how many passwords are to be created. I need to print the results to a file. However, it is printing all of the results into one line. See below.
Here is the code:
import string
import random
print('''---Password Generator---''')
characters = string.punctuation + string.ascii_letters + string.digits
numofpasswd = int(input('How many passwords would you like?: '))
passwdlength = int(input('Please pick amount of characters. Pick more than 8 characters for better security: '))
if passwdlength < 8:
print("Password is less than 8 characters. Please restart program.")
else:
for password in range(numofpasswd):
passwd = ''
for char in range(passwdlength):
passwd += random.choice(characters)
print(passwd)
f = open("pass.txt", 'a')
f.write(passwd)
f = open('pass.txt', 'r')
f.close()
Here is a sample output. I requested 2 passwords with a length of 9:
~Lf>8ohcY
Q*tPR:,
Here is what is written to pass.txt:
~Lf>8ohcYQ*tPR:,
As you can see, it combines the output. Please help.
extra: is there a way to simplify this code as well? Thanks!
Write a newline after each password:
f.write(passwd + '\n')
Also, you shouldn't do
f = open('pass.txt', 'r')
before
f.close()
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")
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)
'Application1': ['Username1', 'Password1']
'Application2': ['Username2', 'Password2']
So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)
hp = open("Passwords.txt","a") #open the file
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ") #make variables to add
hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file
hp.close() #close the file
I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?
As said in a different answer the problem is your string handling when writing to the file. I would recommend to use string formatting:
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
See https://pyformat.info/
Recommended code:
# Ask for variables to add
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ")
# Open file
with open("Passwords.txt", "a") as hp:
# Add line with same format as the rest of lines
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
If you use the with open(...) as ...: you don't have to call the close method, it's called automatically when you exit the with's scope.
Your problem is when you try to write to the file. Change it to
hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']')
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")