So I created python password generator. I want the password created to add itself to a txt file but I cant find a way. Heres the code:
import random
passlen = int(input("enter the length of password "))
s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
p = "".join(random.sample(s,passlen ))
file = open("pass.txt", "a")
file.write("Password: ")
file.close()
print(p)
file = open("pass.txt", "r")
print("Output of Readlines after appending")
print(file.read())
print()
file.close()
CodePudding user response:
with open("pass.txt", "r") as myfile:
myfile.write(p)
hope this help
CodePudding user response:
You are not writing p
into file
. Try:
import random
passlen = 10
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
p = ''.join(random.sample(s, passlen))
with open('pass.txt', 'a') as f:
print(f"password: {p}", file=f)
with open('pass.txt', 'r') as f:
print("Now the contents of pass.txt:")
print(f.read())
Note that with open
is preferred (to open ... close
) in general.