How to view the contents of a file in python - python

I am trying to add a new account in my file which already consist of a username and password of other accounts, after doing it I only want to view the new added accounts or contents of the file like this but have certain distances with each other:
No. Account Name Username Password
1 Facebook admin 123admin
2 Google user 123user
Below is my code for adding a new account in my file:
def Add_account():
account = input("\nEnter the name of the account: ")
username = input(f"Enter the username of your {account}: ")
password = input(f"Enter the password of your {account}: ")
ask = input(f"Do you want to save {account} credentials? [Y|N]: ")
if new_ask == "Y":
with open("info.txt", "a") as file:
file.write("\n" + encrypt(account) + ":" + encrypt(username) + ":" + encrypt(password))
file.close()
Add_account()
How can I view the new accounts only in my file?

Related

Remove new line when appending to file

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

Replace a line in a text file using python

I want to replace some of the contents of my file. I have this code:
username= input("enter your new username")
password= input("enter the new password")
file = open("testfile.txt", "r")
replaced_content = ""
for line in file:
line = line.strip()
new_line = line.replace("username:", "username: " + username)
replaced_content = replaced_content + new_line + "\n"
file.close()
write_file = open("testfile.txt", "w")
write_file.write(replaced_content)
write_file.close()
Here, testfile.txt contains:
username:
password:
The problem is when I input the replacement text, it's being added rather than replaced. For example, when I enter a username, I want to replace the line "username:" by "username: admin"; but when I run the code repeatedly, it gets added repeatedly, thus:
username: admin admin
password:
If my username is already in the text file I want to replace it with an other one and not adding the new to the other. How can I make this work? (I try to not import packages or other things like that in my code.)
Check if the line equal "username:" and only do the replacement then. In this code it will replace the username: in a line "username: admin" with "username: " + username giving you the extra admin at the end
The issue is that you find a "username:" in the line and replace it with "username: " + username. So if you had a line like "username: admin", it would simply replace the username as asked, and it would become "username: admin admin".
Try changing the
new_line = line.replace("username:", "username: " + username)
to
new_line = "username: " + username if line.count("username:") > 0 else line
Try this (untested, please report of any errors found)v
username= input("enter your new username")
password= input("enter the new password")
new_l=[username, password]
write_file = open("testfile.txt", "r+")
lines=write_file.readlines()
for i,j in zip(lines, new_l):
write_file.write(i.strip('\n')+j)
write_file.write('\n')
write_file.close()

How to save a variable to a text file and retrieve it later?

I am trying to make a program to save passwords. How do I take the input and put it into a text file password.txt? Also how would I retrieve that data in the future and print it out?
def display():
print ("Do you want to add a password to get a password? get/add")
response = input()
if response == "get":
savingPasswords()
def savingPasswords():
username = input("Enter username")
username = open ('password.txt', 'w')
password = input ("Enter password")
account = input("What account is this for?")
print ("Login successfully saved!")
while status == True:
display()
you can store your data as a json:
import json
import os
# data will be saved base on the account
# each account will have one usernae and one pass
PASS_FILE = 'password.json'
def get_pass_json_data():
if os.path.isfile(PASS_FILE):
with open(PASS_FILE) as fp:
return json.load(fp)
return {}
def get_pass():
account = input("What account is this for?")
data = get_pass_json_data()
if account not in data:
print('You do not have this account in the saved data!')
else:
print(data[account])
def savingPasswords():
username = input("Enter username")
password = input ("Enter password")
account = input("What account is this for?")
data = get_pass_json_data()
# this will update your pass and username for an account
# if already exists
data.update({
account: {
'username': username,
'password': password
}
})
with open(PASS_FILE, 'w') as fp:
json.dump(data, fp)
print ("Login successfully saved!")
actions = {
'add': savingPasswords,
'get': get_pass
}
def display():
print("Do you want to add a password to get a password? get/add")
action = input()
try:
actions[action]()
except KeyError:
print('Bad choice, should be "get" or "add"')
while True:
display()
The problem was with your second function. I would advise using with open to open and write to files since it looks cleaner and it is easier to read. In your code you never wrote to the file or closed the file. The with open method closes the file for you after the indented block is executed. I would also recommend writing to something like a csv file for organized information like this so it will be easier to retrieve later.
def display():
response = input("Do you want to add a password to get a password? (get/add)\n")
if response.upper() == "GET":
get_password()
elif response.upper() == "ADD":
write_password()
else:
print("Command not recognized.")
exit()
def write_password():
with open("password.csv", "a") as f:
username = input("Enter username: ")
password = input("Enter password: ")
account = input("What account is this for? ")
f.write(f"{username},{password},{account}\n") # separates values into csv format so you can more easily retrieve values
print("Login successfully saved!")
def get_password():
with open("password.csv", "r") as f:
username = input("What is your username? ")
lines = f.readlines()
for line in lines:
if line.startswith(username):
data = line.strip().split(",")
print(f"Your password: {data[1]}\nYour Account type: {data[2]}")
while True:
display()
Write to a file:
password="my_secret_pass"
with open("password.txt","w") as f:
f.write(password)
to read the password from the file, try:
with open("password.txt","r") as f:
password = f.read()
You can use Pickle: a default python package to save data on file
use:
######################
#py3
import pickle
#py2
import cpickle
#################
file = "saves/save1.pickle"
#you can specify a path, you can put another extension to the file but is best to put .pickle to now what is each file
data = {"password":1234, "user":"test"}
#can be any python object :string/list/int/dict/class instance...
#saving data
with open(file,"w", encoding="utf-8") as file:
pickle.dump(data, file)
#retriveing data
with open(file,"r", encoding="utf-8") as file:
data = pickle.load(file)
print(data)
#-->{"password":1234, "user":"test"}
print(data["password"])
#-->1234
it will save the data you put in "data" in the file you specify in "file"
more info about pickle

Python login script using dictionary

I am making a login script for python and it will create passwords and write them to a text file like (username:password). But I want to add a login script that will check to see if the username and password is in the text file.
def reg():
print('Creating new text file')
name = input('Username: ')
passwrd = input('Password: ')
with open("users.txt", "r+") as f:
old = f.read()
f.seek(0)
f.write(name + ":" + passwrd + "\n" + old)
f.close()
def login():
user = input("username: ")
passwrd = input("password: ")
with open('users.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for user,passwrd in credentials:
(This is where i want to add the code)
reg()
login()
I think it would be something like.
for user,passwrd in credentials:
print("found")
else:
print("not found")
If you make credentials a dict, then you can do:
if user in credentials and credentials[user] == password:
//success
else:
//failure
This should work for making credentials be a dict
with open('users.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()])
You just check to see if they match. Note that you need to make the variable names different:
for user2,passwrd2 in credentials:
if (user == user2 and passwrd == passwrd2):
print ("Passed")

Python, How to replace a complete line which contents a string text?

I have a text file which contents the credentials to access a my app, example off my text file
#cat /etc/app/paswords
petter#domain.com $8324dhedberhnnhdbcdhgvged
userhappy#domain.com $2349cmjedcnecbcdfrfrrf8839
the spaces are tab's
I want to change the password hash or the complete line whith a new password
I have the following code:
#cat passreplace.py
domain = "midomain.com"
user = "userhappy"
email = user + "#" + domain
print email
if email in open('/etc/app/passwords').read():
print "User already exist!! one moment change your password"
#code to remplace password
thank you
fileinput is a good choice for this one.
import fileinput
email = username + password
for line in fileinput.input('/etc/app/passwords', inplace=True):
if email in line:
print("User already exists! Change password now!")
username,password = line.split('\t')
old_pass = input("Enter old password: ")
if old_pass != password:
# do something
new_pass = input("Enter new password: ")
confirm = input("Confirm new password: ")
if new_pass != confirm:
# do something
print("\t".join([email, new_pass]), end="")
else:
print(line, end="")

Categories

Resources