Deleting usernames and not via password in a text file - python

Guest = {}
with open('LogIn.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for username,password in credentials:
Guest[username] = password
def DelUser():
DB = open('LogIn.txt',"r+")
username = DB.read()
delete = raw_input("Input username to delete: ")
if delete in username:
<insert code to remove line containing username:password combination>
So, I have a LogIn.txt file with the following username:password combinations:
chris:test
char:coal
yeah:men
test:test
harhar:lololol
I want to delete the username:password combination that I want to in the object "delete"
But the problem is, if I use the
if delete in username:
argument, it'll have to consider the password as well. and example, what if I have two accounts with the same password? Or like the one above. What path can I take for this one? Or am I missing something here?

According to your current DelUser function, you can read the file, remove the line that start with the user to delete, and write a new one:
def DelUser():
# read the current files, and get one line per user/password
with open('LogIn.txt',"r+") as fd:
lines = fd.readlines()
# ask the user which one he want to delete
delete = raw_input("Input username to delete: ")
# filter the lines without the line starting by the "user:"
lines = [x for x in lines if not x.startswith('%s:' % delete)]
# write the final file
with open('LogIn.txt', 'w') as fd:
fd.writelines(lines)

Use
if delete in Guest:
to test if delete is a key in Guest. Since the keys of Guest represent usernames, if delete in Guest tests if delete is a username.
You could use the fileinput module to rewrite the file "inplace":
import fileinput
import sys
def DelUser(Guest):
delete = raw_input("Input username to delete: ")
for line in fileinput.input(['LogIn.txt'], inplace = True, backup = '.bak'):
if delete not in Guest:
sys.stdout.write(line)

Related

How can i delete a couple lines of text that I inputted into a text file in python?

I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes. Im trying to create a function to delete an entry but im not sure how to make the function delete all the lines of information associated with the Username. I want an input asking "Which account to delete" you put the username, and it will delete all information associated with the username in info.txt
Code:
import os.path #Imports os module using path for file access
def checkExistence(): #Checking for existence of file
if os.path.exists("info.txt"):
pass #pass is used as a placeholder bc if no code is ran in an if statement and error comes.
else:
file = open("info.txt", "w") #creates file with name of info.txt and W for write access
file.close()
def appendNew():
#This function will append a new password in the txt file
file = open("info.txt", "a") #Open info.txt use a for appending IMPORTANT: opening a file with w for write will write over all existing data
userName = input("Enter username: ")
print(userName)
os.system('cls')
password = input("Enter password: ")
print(password)
os.system('cls')
website = input("Enter website: ")
print(website)
os.system('cls')
print()
print()
usrnm = "Username: " + userName + "\n" #Makes the variable usrnm have a value of "Username: {our username}" and a new line
pwd = "Password: " + password + "\n"
web = "Website: " + website + "\n"
file.write("----------------------------------\n")
file.write(usrnm)
file.write(pwd)
file.write(web)
file.write("----------------------------------\n")
file.write("\n")
file.close()
def readPasswords():
file = open("info.txt", "r") #Open info.txt with r for read
content = file.read() # Content is everything read from file variable (info.txt)
file.close()
print(content)
checkExistence()
while True:
choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
print(choice)
if choice == "1":
os.system('cls')
appendNew()
elif choice == "2":
os.system('cls')
readPasswords()
elif choice == "3":
os.system('cls')
else:
os.system('cls')
print("huh? thats not an input.. Try again.\n")
I tried making a delete account function by deleting the line which matched the username. My only problem is that it only deletes the line in info.txt with the username, but not the password and website associated with that username.
Firstly, you're using the wrong tool for the problem. A good library to try is pandas, using .csv files (which one can think of as pore program oriented excel files). However, if you really want to use the text file based approach, your solution would look something like this:
with open(textfile, 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
# The above makes a list of all lines in the file without \n char
index = lines.index(username)
# Find index of username in these lines
for i in range(5):
lines.pop(index)
# Delete the next five lines - check your 'appendNew' function
# you're using five lines to write each user's data
print(lines)
f.write("\n".join(lines))
# Finally, write the lines back with the '\n' char we removed in line 2
# Here is your readymade function:
def removeName(username):
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Function that also asks for username by itself
def removeName_2():
username = input("Enter username to remove:\t")
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Usage:
removeName(some_username_variable)
removeName_2()
Again, this is a rather clunky and error prone approach. If you ever change the format in which each user's details are stored, your would have to change the number of lines deleted in the for loop. Try pandas and csv files, they save a lot of time.
If you're uncomfortable with those or you're just starting to code, try the json library and .json files - at a high level they're simple ways of storing data into files and they can be parsed with the json library in a single line of code. You should be able to find plenty of advice online about pandas and json.
If you're unable to follow what the function does, try reading up on try-except blocks and function parameters (as well as maybe global variables).

Storing data in .txt file and retrieving it

I was trying to make some sort of login system,
I have it so that if a username and password are in test.txt (there is multiple ones) it should let you login, I haven't even passed the step of verifying if the username and password are in the txt file and its destroying me, I don't know how to do it and I tried for hours, I made it so "if you find this username in the text file, give me the line number and check if the password this password is in the same line of the username ,(I used split (',')) , if both email and password entered are existent in the txt file and in the same line then..(didn't do that yet).
so it is confusing me, lots of errors, if no errors then it isn't working like I intended, here is my spaghetti code
def test():
with open('test.txt', 'r') as f:
for num, line in enumerate(f,1):
username = line.split(',')
if username in num:
if username == q1:
print("found user in line: " + num)
Line = num
password = line.split(',')
if password in Line:
if password == q2:
print("found pass in line: " + num)
can someone help me fix this and explain to me how storing data in .txt files work and how to retrieve them? YouTube and google didn't help much really, if you can suggest a video that will be cool too, because I'm confused at this point, all I have left is to try MongoDB because it has functions to retrieve data and store it already built in
but as its local on my pc not on the internet, I don't think I will need MongoDB, so that will be an overkill for a local test
With json, you can get it done this way:
JSON File
{
"user1":{"password":"123456"},
"user2":{"password": "abcde"}
}
Python
import json
def test(username, password):
with open("answer.json", "r") as read_it:
data = json.load(read_it)
if data[username][password] == '123456':
print('User found!')
else:
print('User or password doesn\'t exist')
test('user1', 'password')
If you want to use a text file, then as a simple example:
cat test.txt
aklaver, dog
adrian, cat
alklaver, fish
user_name = 'aklaver'
with open('test.txt', 'r') as pwd_file:
lines = pwd_file.readlines()
for line in lines:
user, pwd = line.split(',')
if user == user_name:
print(pwd)
dog

Checking if string exists in file using while loop

I am new to Python and am having trouble with looping while checking strings in a file. For this program, I am checking to see if a username that the user wants to create already exists. If the username already exists in the file, the program prompts the user to enter another username. The loop ends when the user enters a username that is not in the file. Here is the relevant code:
# Prompting for username and password
username = input("Enter your username: ")
password = input("Enter your password: ")
# open password file
f = open("password.txt", "r")
# while username exists in file
while username in f.read():
username = input("Enter your username: ")
f.close()
If I enter a username that exists in the password file, the program does prompt me to enter another username; however, when I enter the same username, the program does not stay in the loop. Any ideas on why this is occurring?
When you run f.read() Python will read the file in and then continue onto the next line of the file in the next iteration. It wont go back to the top of the file. So it exits the loop since the username in the next line of the file is either an empty string or another name. To fix this you could use a context manager like so:
# Prompting for username and password
username = input("Enter your username: ")
password = input("Enter your password: ")
# read in the file data
with open('password.txt') as f:
data = f.read()
# while username exists in file
while username in data:
username = input("Enter your username: ")
Then depending on how the data is structured in your .txt file then you can call split() on data if it's using a new line.
There is no condition to check whether the new username is in the file or not.
Maybe an easier way to do this would be to use the following approach?
username = input("Enter your username: ")
password = input("Enter your password: ")
# open password file
f = open("password.txt", "r")
data = f.read()
# while username exists in file
while username in data:
new = input("Enter your username: ")
if new in data:
continue
else:
break
username = new
f.close()
This is because you are using f.read() in the while condition.
f.read reads the whole content of the file at once and there's nothing else to read from file, leading to the end of while loop.
If you want to check for usernames in the file, I'd suggest you create a list of usernames that you read from the file and use it in your while loop for checking.
If your file has contents:
username1, username2, ...
You can do
listOfUsernames = f.read().split(',')
and then use this for checking in while loop.

delete row from file using csv reader and lists python

there are similar questions on SO to this but none that deal with the specifics that I require.
I have the following code that seeks to delete a row in a file, based on specified user input. The methodology is to
Read file into a list
Delete the relevant row in the list (ideally while reading in the list?)
Over-write file.
It's 2 and 3 that I would like some guidance on as well as comments as to the best solution (for beginners, for teaching/learning purposes) to carry out this sort of simple delete/edit in python with csv reader.
Code
""" ==============TASK
1. Search for any given username
2. Delete the whole row for that particular user
e.g.
Enter username: marvR
>>The record for marvR has been deleted from file.
"""
import csv
#1. This code snippet asks the user for a username and deletes the user's record from file.
updatedlist=[]
with open("fakefacebook.txt",newline="") as f:
reader=csv.reader(f)
username=input("Enter the username of the user you wish to remove from file:")
for row in reader: #for every row in the file
if username not in updatedlist:
updatedlist=row #add each row, line by line, into a list called 'udpatedlist'
print(updatedlist)
#delete the row for the user from the list?
#overwrite the current file with the updated list?
File contents:
username,password,email,no_of_likes
marvR,pass123,marv#gmail.com,400
smithC,open123,cart#gmail.com,200
blogsJ,2bg123,blog#gmail.com,99
Update
Based on an answer below, I have this, but when it overwrites the file, it doesn't update it with the list correctly, not sure why.
import csv
def main():
#1. This code snippet asks the user for a username and deletes the user's record from file.
updatedlist=[]
with open("fakefacebook.txt",newline="") as f:
reader=csv.reader(f)
username=input("Enter the username of the user you wish to remove from file:")
for row in reader: #for every row in the file
if row[0]!=username: #as long as the username is not in the row .......
updatedlist=row #add each row, line by line, into a list called 'udpatedlist'
print(updatedlist)
updatefile(updatedlist)
def updatefile(updatedlist):
with open("fakefacebook.txt","w",newline="") as f:
Writer=csv.writer(f)
Writer.writerow(updatedlist)
print("File has been updated")
main()
It appears to print the updatedfile correctly (as a list) in that it removes the username that is entered. But on writing this to the file, it only prints ONE username to the file.
Any thoughts so I can accept a final answer?
if username not in updatedlist:
To me should be:
if row[0] != username:
Then in a second loop you write updatedlist into your csv file.
I would personnally write everything in another file while reading, then in the end delete the old file and replace it by the new one, which makes it one loop only.
Edit:
replace updatedlist=row with updatedlist.append(row): the first one means overwriting updatedlist with one row while the second one means adding one more row to it.
writerow writes one row, and you give it a list of rows.
Use writerows instead and your writing function will work.
You nearly made it all by yourself, which was my objective.
Some other answers already give you better (faster, cleaner ...) ways, so I won't.
I recommend this approach:
with open("fakefacebook.txt", 'r+') as f:
lines = f.readlines()
f.seek(0)
username = input("Enter the username of the user you wish to remove from file: ")
for line in lines:
if not username in line.split(',')[0]: # e.g. is username == 'marvR', the line containing 'marvR' will not be written
f.write(line)
f.truncate()
All lines from the file are read into lines. Then I go back to the beginning position of the file with f.seek(0). At this point the user is asked for a username, which is then used to check each line before writing back to the file. If the line contains the username specified, it will not be written, thus 'deleting' it. Finally we remove any excess with f.truncate(). I hope this helps, if you have any questions don't hesitate to ask!
I tried to stick to your code: (EDIT: not elegant, but as near as possible to the OPs code)
""" ==============TASK
1. Search for any given username
2. Delete the whole row for that particular user
e.g.
Enter username: marvR
>>The record for marvR has been deleted from file.
"""
import csv
#1. This code snippet asks the user for a username and deletes the user's record from file.
updatedlist=[]
with open("fakefacebook.txt",newline="") as f:
reader=csv.reader(f)
username=input("Enter the username of the user you wish to remove from file:")
content = []
for row in reader: #for every row in the file
content.append(row)
# transpose list
content = list(map(list, zip(*content)))
print(content)
index = [i for i,x in enumerate(content[0]) if x == username]
for sublist in content:
sublist.pop(index[0])
print(content)
# transpose list
content = list(map(list, zip(*content)))
#write back
thefile = open('fakefacebook.txt', 'w')
for item in content:
thefile.write("%s\n" % item)
But I would suggest to use numpy or pandas
Something like this should do you, using the csv module. Since you have structured tabular data with defined columns you should use a DictReader and DictWriter to read and write to/from your file;
import csv
with open('fakefacebook.txt', 'r+') as f:
username = input("Enter the username of the user you wish "
"to remove from file:")
columns = ['username', 'password', 'email', 'no_of_likes']
reader = csv.DictReader(f, columns)
filtered_output = [line for line in reader if line['username'] != username]
f.seek(0)
writer = csv.DictWriter(f, columns)
writer.writerows(filtered_output)
f.truncate()
This opens the input file, filters the out any entries where the username is equal to the desired username to be deleted, and writes what entries are left back out to the input file, overwriting what's already there.
And for another answer: write to a new file and then rename it!
import csv
import os
def main():
username = input("Enter the username of the user you wish to remove from file:")
# check it's not 'username'!
#1. This code snippet asks the user for a username and deletes the user's record from file.
with open("fakefacebook.txt", newline="") as f_in, \
open("fakefacebook.txt.new", "w", newline="") as f_out:
reader = csv.reader(f_in)
writer = csv.writer(f_out)
for row in reader: #for every row in the file
if row[0] != username: # as long as the username is not in the row
writer.writerow(row)
# rename new file
os.rename("fakefacebook.txt.new", "fakefacebook.txt")
main()

How to iterate through a file and create new string variables by line

I read through docs, but still cannot figure out how to open a file, read each line, store that line as a new string variable (for now).
I tried:
file = file.open ("users.txt", r)
for user in users:
user = users.readline ()
''' this is where I'd like to add something that creates user, user, until EOF '''
file.close ()
It is unclear what you are trying to do.
Here is an outline (if I am understanding it) in Python idiom:
your code -- commented:
# file = file.open ("users.txt", r) NO! just use open' and don't use 'file' for a name
# for user in users: What is 'users'?
# user = users.readline () # if this is a file, just do 'for user in users: ...'
''' this is where I'd like to add something that creates user, user, until EOF '''
# file.close () # not necessary if you use `with`
Corrected:
with open("users.txt", r) as users:
for user in users:
# if each line of the file is a 'user' this gives you one user at a time
Try this
file = open("myfile.txt", "r")
lines = file.readlines()
str = ''
for i in range(len(lines)):
str += lines[i].rstrip('\n') + ' '
print str
Hope that helps.

Categories

Resources