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

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="")

Related

How to view the contents of a file in 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?

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 do I select certain lines in a text file from python script?

So I'm making a python script where you can create an account and that account is saved in a text file. When you try to log in, it will look in the text file for your username and then move down a line for the password but I don't know how to move down a line after finding the username. Any help would be appreciated. :)
Update -
import time
import sys
print ("Do you have an account?")
account = input()
if account == "Yes":
print ("Enter your username")
enterUsername = input()
with open ("Allusers.txt") as f:
if enterUsername in f.read():
print ("Enter your password")
enterpassword = input()
if enterpassword in f.read():
print ("Logged in")
if enterpassword not in f.read():
print ("Wrong password")
if account == "No":
print ("Create a username")
createUsername = input()
with open ("Allusers.txt") as f:
if createUsername in f.read():
print ("Username already taken")
sys.exit()
if createUsername not in f.read():
print ("Create a password")
createPassword = input()
with open ("Allusers.txt") as f:
if createPassword in f.read():
print ("Password not available")
sys.exit()
if createPassword not in f.read():
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createUsername + "\n")
file_object.close()
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createPassword + "\n")
file_object.close()
print ("Done")
This is still work in progress and most likely still has errors here and there.
Assumin that your file look like this:
Adam
password
John
12345678
Horacy
abcdefg
Romek
pass1234
You can try this example:
user = "Horacy"
password = "abcdefg"
with open( "users.txt", "r" ) as file:
for line in file:
if user == line.strip():
if password == file.readline().strip():
print( "Correct" )
break
As stated if someones password equals someones username iterating over all lines and checking may return faulty results you'll want to check only usernames as you iterate, so zipping every other line you can check the username only and return the password:
def get_password(file, username):
with open(file, "r") as f:
data = f.readlines()
for user, pw in zip(data[::2], data[1::2]):
if user.strip() == username:
return pw.strip()
def get_password(file, username):
lines = open(file, "r").readlines() # get the lines from the file
for i, line in enumerate(lines):
if line == username: # if the current is the username, return the following line
return lines[i + 1]
You should only search in usernames. The data[::2] will select usernames.
with open("filename", "r") as f:
data = f.read().splitlines()
email = "email#email"
if email in data[::2]:
id_email=data[::2].index(email)
row=id_email*2-1
password=data[row+1]

I'm trying a beginner project to make like a login and register program with a txt file "serving as a database" in python

I want this: if the user inputs an email that already exists in the .txt file, the output should be that this email already exists there.
I don't want help with anything else, just this thing. And I'm aware that this is not finished, just got stuck here...
This is the code:
choice=input("Choose if you want to register(1) or login(2): ")
if int(choice)==1:
reg=input("Input your email: ")
passreg1=input("Create your password: ")
passreg2=input("Confirm your password: ")
f=open("email.txt","r")
lines=str(f.read())
if reg==any(lines):
print("You already have an account!")
else:
if str(passreg1)==str(passreg2):
#f=open("email.txt", "a")
#f.write("\n" + reg)
#f.close()
print("Account registered successfully.")
else:
print("Passwords do not match.")
else:
log=input("Input your email: ")
passlog=input("Input your password: ")
print("Login successful!")
Also, in the text file I just have emails arranged like this:
test#gmail.com
hello#yahoo.com
instead of if reg == any(lines):, to check if reg is in the list lines, we do: if reg in lines:
Replace these lines:
f=open("email.txt","r")
lines=str(f.read())
if reg==any(lines):
print("You already have an account!")
by these:
with open("email.txt", "r") as f:
lines = f.read()
if reg in lines:
print("You already have an account!")
If you have a txt with an email per line you can just read the file content as a string and then use the string splitlines() method to convert it as a list of lines. After that you can check if any entry of the list (a line) contains the email you are looking for:
lines=str(f.read().splitlines())
if reg in lines:
# ...

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")

Categories

Resources