Listing a single entry by selecting ID and updating a single entry in Python - python

I'm creating a program which I will run in bash/terminal. When run, the programme is supposed to prompt the user with the question "Please add user ID". After entering an ID (not index) it should display the selected ID. eg: 1 should display the whole line of Will Smith.
The code I had implemented is as below but it displays the index. If I select 1, it would display the line of Jane Doe. Where am I going wrong?:
def show_single_user():
initialise = []
input_user_id = input("Please add user index.")
for i, row in enumerate(open("file.txt")):
if str(i) in input_user_id:
initialise.append(row)
print(initialise)
I have a similar issue when I want to delete a user ID, it randomly deletes a user instead of the ID requested. I don't want to delete based on index which starts at zero. Below is the code.
def delete_user_id():
text_file = open("file.txt", "r")
target_id = text_file.readlines()
text_file.close()
user_input = input("Add the ID to delete:")
del target_id[1]
new_file = open("file.txt", "w+")
# For loop iterating to delete the appropriate line
for line in target_id:
new_file.write(line)
new_file.close()
print("User ID successfully removed!")
input("Press any key to return to main menu")
delete_user_id()
Thanks

You should read the ID from the file.
def show_single_user():
initialise = []
input_user_id = input("Please add user index.")
for line in open("file.txt"):
id = line.split()[0]
if id == input_user_id:
initialise.append(row)
print(initialise)

Related

How to extract specific data from a text file in Python?

This is a text file accountinfo.txt:
Luke TonyHawk123! luke33#gmail.com
Cindy JasonVoorhees123! cindy5#yahoo.com
I want to ask the user for their email to print the values (i.e. their username and password) on the left. For example, if the user inputs luke33#gmail.com, it should return Luke and TonyHawk123.
I've tried using strip and split, but my logic is wrong.
Work I've done so far:
account_file = open("accountinfo.txt")
email_string = account_file.read().strip().split()
while True:
email_account = input("Enter the email linked to your account: \n")
if email_account == "":
continue
if email_account in email_string:
# ???
else:
print("This email doesn't exist in our records.")
main()
You can apply csv.reader here:
import csv
with open("accountinfo.txt") as f:
reader = csv.reader(f, delimiter=" ")
email = input("Enter the email linked to your account: \n")
for row in reader:
if row and row[2] == email:
print(" ".join(row[:2]))
break
else:
print("This email doesn't exist in our records.")
main()
You can also split each line manually:
with open("accountinfo.txt") as f:
email = input("Enter the email linked to your account: \n")
for line in f:
if email and email in line:
print(line.rsplit(" ", 1)[0])
break
else:
print("This email doesn't exist in our records.")
main()
I don´t know how the information of each e-mail is arranged but if they´re in the same file. I did a similar program, but the information of each username was separated with a sting like this: "----------------". So I iterated through lines until it found the e-mail. Once it found it, I would print every line until it found another "----------------". So all the user´s information was between those lines. You can do something similar depending on how your information is arranged. You can iterate through the lines of the file with:
validation = False
for line in file:
if email in line:
validation = True
while line != "---------------":
print(line, end="")
if validation == False:
print("This email doesn't exist in our records.")

Deleting a person from a file not in a list

For class I need to put names into a file then have the user type in the name they want to delete, and it deletes them. I almost have it it just deletes 2 people at once and I'm not sure why.
import os
def main():
found=False
search=input("Who would you like to delete? ")
student_grades = open("student_grades.txt", 'r')
temp_file= open('temp.txt', 'w')
descr = student_grades.readline()
while descr != '':
qty = (student_grades.readline())
descr = descr.rstrip('\n')
if descr != search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found = True
descr = student_grades.readline()
student_grades.close()
temp_file.close()
os.rename('temp.txt', 'grades.txt')
if found:
print('The file has been updated.')
else:
print('That student was not found in the file.')
main()
There is also 2 files. student_grades.txt that has the names in it, and temp.txt with nothing. When typing in the name of the person, it can find them but it deletes 2 people instead of the one that was searched.
If you are using Python3.6+
from pathlib import Path
fname = "student_grades.txt"
def bak_file(old_name, new_name=None):
if new_name is None:
new_name = old_name + '.bak'
Path(new_name).write_bytes(Path(old_name).read_bytes())
print('-->', f'cp {old_name} {new_name}')
def main():
bak_file(fname)
lines = Path(fname).read_text().splitlines()
search = input("Who would you like to delete? ").strip()
if search in lines:
updated_lines = [i for i in lines if i != search]
Path(fname).write_text('\n'.join(updated_lines))
print(f'The file {fname} has been updated.')
else:
print('That student was not found in the file.')
if __name__ == '__main__':
main()
Are you sure it deletes two people? This qty = (student_grades.readline()) ... temp_file.write(str(qty) + '\n') makes me think that you might be adding unwanted new lines (no strip when getting the qty, but adding a new line when rewriting it), which might look like you removed two instead of one?
Eraw got it. It works now. I was following a program from my book and they had a slightly different scenario. I deleted qty = (student_grades.readline()) and temp_file.write(str(qty) + '\n') and this deletes only what needs to be deleted. Thanks!

How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()

How to grab a certain word from a .txt file given what it begins and ends with

DISCLAIMER:
I'm using python 3!
FUNDEMENTAL CODE:
So I have this code:
def login(userlogin):
with open('usernames.txt') as input_data: # Grabs username from usernames.txt CHANGE DOESN'T WORK FOR MULTIPLE PEOPLE
for user in input_data:
if user.strip() == userlogin:
break
for user in input_data:
if user.strip() == '0':
break
print(user)
while(True):
userinput = input('')
login(userinput)
and also .txt file in the same directory, called usernames.txt which you can see here:
admin010
guest020
admin01030
user040
DESIRE:
I want the code to output the username corresponding in the .txt file based on the name inputted, so for example, if you inputted 'admin' it would find text in the text document that starts with admin and find its ending which is always a '0' and output admin010. However, I want it to make sure, when you type admin01 it would output admin01030. So the usernames are in the form, name + value (2 digits i.e. a value of 7 would be 07) + a zero ('0' string).
PROBLEM:
The code isn't working, no matter my input it always outputs the last word in the .txt document. I'm not sure why, any help would be great.
If the format is "name + two-digits + 0", then you want to match the name with a line less the last three characters:
for user in input_data:
if userlogin == user.rstrip()[:-3] # strip trailing whitespace and remove last 3 chars
print(user)
Can be written fairly compactly in this way, if I understand you.
def login(userlogin):
with open('usernames.txt') as usernames:
for line in usernames:
username = line.strip()
if username.startswith(userlogin+'0') and len(username)==len(userlogin)+3:
print (username)
return
print ('no match')
for poss in ['admin', 'admin01', 'guest', 'user']:
print (poss, ': ', end=''); login(poss)
Output:
admin : admin010
admin01 : admin01030
guest : guest020
user : user040
Hi please see below code. But I need to know why admin01 would match admin01030 only? since admin010 also starts with admin01
def login(userlogin):
with open(
'usernames.txt') as input_data: # Grabs username from usernames.txt CHANGE DOESN'T WORK FOR MULTIPLE PEOPLE
for user in input_data:
if user.strip() == '0':
break
if user.strip().startswith(userlogin, 0, len(userlogin)):
break
print(user)
while True:
userinput = input('')
login(userinput)
What you want to do is basically check if a string has a substring.
In the below example when the button is pressed, it checks if the file 'usernames.txt' that is in the same directory, has a string that matches exactly the user input before reaching the last 3 letters which are reserved for value and zero. Then parses it to name, value and '0':
import tkinter as tk
def login():
with open('usernames.txt') as fin:
users_list = fin.readlines()
for user in users_list:
user = user.strip() # to lose \n
if user[:-3] == query.get():
nam_lbl['text'] = user[:-3]
val_lbl['text'] = user[-3:-1]
zero_lbl['text'] = user[-1]
root = tk.Tk()
query = tk.Entry(root)
nam_lbl = tk.Label(root, text="Name: ")
val_lbl = tk.Label(root, text="Value: ")
zero_lbl = tk.Label(root, text="Zero: ")
tk.Button(root, text="Login", command=login).pack()
# layout
query.pack()
nam_lbl.pack()
val_lbl.pack()
zero_lbl.pack()
root.mainloop()

Python- Saving Results to a File and Recalling Them

I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.
The program gives the user the ability to remove, add, or find a student. Here is the code:
students={}
def add_student():
#Lastname, Firstname
name=raw_input("Enter Student's Name")
#ID Number
idnum=raw_input("Enter Student's ID Number")
#D.O.B.
bday=raw_input("Enter Student's Date of Birth")
students[idnum]={'name':name, 'bday':bday}
def delete_student():
idnum=raw_input("delete which student:")
del students[idnum]
def find_student():
print "Find"
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
add_student()
elif selection == '2':
delete_student()
elif selection == '3':
find_students
elif selection == '4':
break
else:
print "Unknown Option Selected!"
The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.
I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:
f = open("myfile.txt", "a")
I'm new to Python so any help would be appreciated. Thanks so much.
It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:
with open('nameOfYourSaveFile', 'w') as saveFile:
#.write() does not automatically add a newline, like print does
saveFile.write(myString + "\n")
Here's an answer that explains the different arguments to open, as in w, w+, a, etc.
As an example, say we have:
with open('nameOfYourSaveFile', 'w') as saveFile:
for i in xrange(10):
saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")
To read the file back, we do:
names = []
numbers = []
emails = []
with open('nameOfYourSaveFile', 'r') as inFile:
for line in inFile:
#get rid of EOL
line = line.rstrip()
#random example
names.append(line[0])
numbers.append(line[1])
emails.append(line[2])
#Or another approach if we want to simply print each token on a newline
for word in line:
print word
import pickle,os
if os.path.exists("database.dat"):
students = pickle.load(open("database.dat"))
else:
students = {}
... #your program
def save():
pickle.dump(students,open("database.dat","w"))

Categories