In: Computer Science
This is all in Python. Also, the names come from a .txt file that i have created with 3 names on it(Jim,Pam,Dwight).
Main Function. Write a program where the user enters a name. Using the read function, check to see if the name is in the text document. If it is, respond back to the user the name is found within the list.
Read Function. The read function should return the contents of the text document as a list.
EXAMPLE OUTPUT
Please enter a name: Jim
Jimis found in the list.
Enter another name (Y/N): Y
Please enter a name: Andy
Sorry, Andy was not found in the list. Would you like to add it?
(Y/N): Y
Andrew has been added to the list.
Enter another name (Y/N): N
Write Function. The write function should take the list and override the file with the new names list in reverse alphabetical order with a hard return after each name.
CODE:
#read function
def read():
file = open('names.txt','r')
#reading all the lines and removing the char '\n' from the
#end of each line
lines = [x.split('\n')[0] for x in file.readlines()]
file.close()
return lines
#write function
def write(lines):
#sotring the list in reverse
lines = sorted(lines,reverse = True)
#opening the file
file = open('names.txt','w')
#writing to the file after hard returning after each name
for i in lines:
file.write(i+'\n')
file.close()
def main():
#reading the file by calling the read function
lines = read()
choice = 'Y'
#while the user wants to enter a new name
while(choice.lower() == 'y'):
#user enters a name
name = input('Please enter a name: ')
if(name in lines):
#if the name is found in list (case-sensitive search)
print('{} found in list:'.format(name))
else:
#if it is not found in the list
print('Sorry, {} was not found in the list. Would you like to add
it?'.format(name))
add = input('(Y/N): ')
#if the user wants to add it to the list
if(add.lower() == 'y'):
#the name is added
lines.append(name)
print('{} has been added to the list'.format(name))
#asking the user to enter another name or not
choice = input('Enter another name (Y/N): ')
#when the user quits the file is updated with a new list
write(lines)
#calling the main function
main()
___________________________________________
CODE IMAGES AND OUTPUT:
________________________________________________
names.txt before executing the program
names.txt after executing the program:
_______________________________________________
Feel free to ask any questions in the comments section
Thank You!