I have been testing my code for the past few hours and I am stumped. This program takes a text file of names, turns the names into a list, prints the names, sorts the names, prints the sorted names, then allows you to search through the list. Everything seems to be working fine, but the one issue I have is exiting the while loop. If y or Y is selected you can search again, but that also happens if anything else is selected. I added a print statement outside the loop so if anything other than y is selected then the program should end with that last printed string, but it doesn't seem to be working. Does anyone have any ideas about why it isn't working and what I could change to get it to work?
Thank you for your time.
#define the main function
def main():
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#call input name function
names = input_name()
#call print name function
print_name(names)
#sort the printed list
names.sort()
#call the print name function
print_name(names)
#call the output name function
output_name(names)
#call the search name function
search_name(names)
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
#print if anything other than y or Y is selected
print()
print('Goodbye!')
#define the input function
def input_name():
#open the names.txt file
infile = open('names.txt', 'r')
#read contents into a list
names = infile.readlines()
#close the file
infile.close()
#strip the \n from each element
index = 0
while index < len(names):
names[index] = names[index].rstrip('\n')
index += 1
#return the list back to main function
return names
#define the print name function
def print_name(names):
#print the contents of the list
for name in names:
print(name)
#define the output name function
def output_name(names):
#open file for writing
outfile = open('sorted_names.txt', 'w')
#write the list to the file
for item in names:
outfile.write(item + '\n')
#close the file
outfile.close()
#return to main function
return
#define the search name function
def search_name(names):
#add a user input to search the file
search = input('Enter a name: ')
#determine whether the name is in the list
if search in names:
#get the names index
name_index = names.index(search)
#print the name was found and give the items index
print(search, "was found in list. This item's index is", name_index)
else:
#print the item was not found
print(search, 'was not found in the list.')
main()
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
You never set keep_going to something else. Instead, you ask the user to enter y to continue but store it in search_again (which is then thrown away). You will want to change that to store the value in keep_going.
You are testing keep_going, but setting search_again
Replace line 29 which states:
search_again = input('Would you like to make another search?(y for yes): ')
with the following:
keep_going = input('Would you like to make another search?(y for yes): ')
Because when you enter y or Y then you are defining the variable search_again to that letter not the variable keep_going which is needed to change for the loop to stop.
Related
I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
As you can see below I am trying to make a program that takes a file called names.txt, breaks it down into a list with .split('/n'), then adds a password for each user in the list. For some reason the for look treats the list as if it were a string, so instead of treating it like:
Bob
Charley
Ron
It breaks it down like:
B
o
b
C
h
....
Thus giving each letter a password instead of the list itself.
What am I doing wrong?
Is there a way I can test to see what the for loop is actually being given?
I have been playing with it to see if it were being given a string, but the list appears to be clealy a list when printed, so why would it be getting treated like a string in the for loop?
def importNames():
try:
file = open("names.txt", "r")
contents = file.read()
print(contents)
file.close()
return contents
except:
print("The file was not found.")
print("Make sure you have a file called \"names.txt\" in the working directory (where you ran this program)")
exit()
def createPasswordList(nameList):
print("They are being given the standard password of \"p#ssw0rd.\"")
#nameList = ["Pickles", "Bob's", 'wow zers john'] #This is for testing purposes. It works just fine, but the original nameList breaks down badly.
passList = []
#for x, value in enumerate(nameList):
for i in nameList:
print(i)
passList.append("p#ssw0rd")
print(passList)
return passList
def createUsers(nameList, passwordList): #takes in a list of usernames, then adds creates them.
for i in nameList:
print("This will do something soon.")
#encPass = crypt.crypt(passwordList[i],"22") #22 is a salt number, use crypt per useradd manual
#os.system("useradd -p " + encPass + " " + nameList[i]) #useradd -p encryptedpass username
def convertNamesToList(originalList):
print("Converting names.") #Use newline as a delimiter
newList = originalList.split('\n')
print(newList)
return newList
def convertNameToUsernames(originalNames):
print("Creating usernames")
print("This program is used to make some users.")
print("If you import a file, have it in the working directory called \"names.txt\".")
print("Would you like to import names or add them manually? (n/m)")
answer = input()
if (answer is 'm' or answer is 'M'):
createUser()
print("The user gets created. Good job.")
else:
originalNames = importNames() #this will return a string of the file.
convertNamesToList(originalNames) #convert the string to sets of names. Use newlines as delimiters.
#convert the names to usernames
print("Do the users have passwords? (y/n)")
#answer = input()
answer = 'n' ###FORCE###
if (answer is 'n' or answer is 'N'):
passwordList = createPasswordList(originalNames)
You're never doing anything with the return value from convertNamesToList. You don't store it anywhere. Then you pass originalNames, which is a string (you even indicate this in a comment) to createPasswordList.
I think you want something like:
originalNames = importNames() #this will return a string of the file.
listOfNames = convertNamesToList(originalNames) #convert the string to sets of names. Use newlines as delimiters.
#convert the names to usernames
print("Do the users have passwords? (y/n)")
#answer = input()
answer = 'n' ###FORCE###
if (answer is 'n' or answer is 'N'):
passwordList = createPasswordList(listOfNames)
It looks like your nameList is actually a string. Assuming that you have one name per line of the names.txt file, Try this:
def importNames():
try:
file = open("names.txt", "r")
contents=[]
for line in file.read():
contents.append(line)
print(contents)
file.close()
return contents
You then no not need to convert it to a list later.
I have got it to work, except the list doesn't save the inputs properly; it just lists them as three periods. This is the code:
names = []
i=0
while 1:
i+=1
name=input("Please enter the name")
if name==" ":
break
names.append(names)
print(names)
Change names.append(names) to names.append(name), since you want to append name to the list names (just a typo I guess).
Also if name == " " must be changed to if name == "", since if the user presses enter without providing any name, the input is an empty string, not a white space.
Correct code here:
names = []
i = 0
while True:
i += 1
name = input("Please enter the name ")
if name == "":
break
names.append(name)
print(names)
Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.
def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined namelist = 0, making it a number. Instead, namelist needs to be an actual list for you to add or append anything to it. Also, you're append() method is not necessary since once you define namelist as a list, you can use the built-in list.append() method, without having to write your own method.
So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.
Since you don't have any main() method, you can define namelist on
the first line of code, before any other code, so that it is
referenced in each method:
namelist = [] # an empty list
Change addmember() method to:
def addmember():
name = raw_input("Type in a name to add: ")
namelist.append(name)
Since namelist is a list, we can use the built-in len() method on nameslist to check if it's empty when printing out its contents (if any):
def printmembers():
if len(namelist) > 0: # Get the length of the list
print(namelist)
else:
print("List is empty")
Now that the Add() menu option is working for adding a name to the namelist, you should be able to implement removing, and editing names to the list using similar logic.
You should consider initializing the list to be empty instead of zero (unless you want that element).
namelist = list()
Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.
def addmember():
name = input("Type in a name to add: ")
namelist.append(name)
If you did want to make your own append method you should understand that the variables in the function definition are inputs, so just saying def append(name) won't perform any action. In this case name is the identifier you are applying to the input argument. You could just as easily call it anything you wanted. A good way to understand this is by assigning the argument a different variable name than the one you pass it. Like this:
def append(nameToAppend):
namelist.append(nameToAppend)
You can call your append method in addmember like this:
def addmember():
name = input("Type in a name to add: ")
append(name)
After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.
In your append method you have to add the name you get to your namelist, like how you do in the editmember method.
I've just undertaken my first proper project with Python, a code snippet storing program.
To do this I need to first write, then read, multiple lines to a .txt file. I've done quite a bit of googling and found a few things about writing to the file (which didn't really work). What I have currently got working is a function that reads each line of a multiline input and writes it into a list before writing it into a file. I had thought that I would just be able to read that from the text file and add each line into a list then print each line separately using a while loop, which unfortunately didn't work.
After going and doing more research I decided to ask here. This is the code I have currently:
'''
Project created to store useful code snippets, prehaps one day it will evolve
into something goregous, but, for now it's just a simple archiver/library
'''
#!/usr/local/bin/python
import sys, os, curses
os.system("clear")
Menu ="""
#----------- Main Menu ---------#
# 1. Create or edit a snippet #
# 2. Read a snippet #
# 0. Quit #
#-------------------------------#
\n
"""
CreateMenu ="""
#-------------- Creation and deletion --------------#
# 1. Create a snippet #
# 2. Edit a snippet #
# 3. Delete a snippet (Will ask for validation) #
# 0. Go back #
#---------------------------------------------------#
\n
"""
ReadMenu="""
#------ Read a snippet ------#
# 1. Enter Snippet name #
# 2. List alphabetically #
# 3. Extra #
# 0. Go Back #
#----------------------------#
"""
def readFileLoop(usrChoice, directory):
count = 0
if usrChoice == 'y' or 'n':
if usrChoice == 'y':
f = open(directory, 'r')
text = f.read()
f.close()
length = len(text)
print text
print length
raw_input('Enter to continue')
readMenu()
f.close()
elif choice == 'n':
readMenu()
def raw_lines(prompt=''):
result = []
getmore = True
while getmore:
line = raw_input(prompt)
if len(line) > 0:
result.append(line)
else:
getmore = False
result = str(result)
result.replace('[','').replace(']','')
return result
def mainMenu():
os.system("clear")
print Menu
choice = ''
choice = raw_input('--: ')
createLoop = True
if choice == '1':
return creationMenu()
elif choice == '2':
readMenu()
elif choice == '0':
os.system("clear")
sys.exit(0)
def create():
os.system("clear")
name = raw_input("Enter the file name: ")
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
while os.path.exists(dire):
os.system("clear")
print("This snippet already exists")
name = raw_input("Enter a different name: ")
dire = ('shelf/'+name+'.txt')
print("File created\n")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
else:
print("File created")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
print text
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
def readMenu():
os.system("clear")
name = ''
dire = ''
print ReadMenu
choice = raw_input('--:')
if choice == '1':
os.system("clear")
name = raw_input ('Enter Snippet name: ')
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
choice = ''
choice = raw_input('The Snippet exists! Open? (y/n)')
'''if not choice == 'y' or 'n':
while (choice != 'y') or (choice != 'n'):
choice = raw_input('Enter \'y\' or \'n\' to continue: ')
if choice == 'y' or 'n':
break'''
readFileLoop(choice, dire)
else:
raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back
readMenu()
elif choice == '0':
os.system("clear")
print Menu
def creationMenu(): ###### Menu to create, edit and delete a snippet ######
os.system("clear")
print CreateMenu
choice = raw_input('--: ')
if choice == '1': ### Create a snippet
os.system("clear")
print create()
print creationMenu()
elif choice == '2':
os.system("clear") ### Edit a snippet
print ("teh editon staton")
raw_input()
print creationMenu()
elif choice == '3':
os.system("clear") ### Delete a snippet
print ("Deletion staton")
raw_input()
print creationMenu()
elif choice == '0': ### Go Back
os.system("clear")
######## Main loop #######
running = True
print ('Welcome to the code library, please don\'t disturb other readers!\n\n')
while running:
mainMenu()
######## Main loop #######
Tl;Dr: Need to write and read multiline text files
The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format e.g ['line1', 'line2', 'line3'] which is making it difficult to read as multilines because I can't get it to be read as a list, when I tried it added the whole stored string into one list item. I don't know if I'm writing to the file correctly.
OK, so the problem is with writing the file. You're reading it in correctly, it just doesn't have the data you want. And the problem is in your raw_lines function. First it assembles a list of lines in the result variable, which is good. Then it does this:
result = str(result)
result.replace('[','').replace(']','')
There are two small problems and one big one here.
First, replace:
Return[s] a copy of the string with all occurrences of substring old replaced by new.
Python strings are immutable. None of their methods change them in-place; all of them return a new string instead. You're not doing anything with that new string, so that line has no effect.
Second, if you want to join a sequence of strings into a string, you don't do that by calling str on the sequence and then trying to parse it. That's what the join method is for. For example, if your lines already end with newlines, you want ''.join(result). If not, you want something like '\n'.join(result) + '\n'. What you're doing has all kinds of problems—you forgot to remove the extra commas, you will remove any brackets (or commas, once you fix that) within the strings themselves, etc.
Finally, you shouldn't be doing this in the first place. You want to return something that can be passed to writelines, which:
Write[s] a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
You have a list of strings, which is exactly what writelines wants. Don't try to join them up into one string. If you do, it will run, but it won't do the right thing (because a string is, itself, a sequence of 1-character strings).
So, if you just remove those two lines entirely, your code will almost work.
But there's one last problem: raw_input:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
But writelines:
… does not add line separators.
So, you'll end up with all of your lines concatenated together. You need the newlines, but raw_input throws them away. So, you have to add them back on. You can fix this with a simple one-line change:
result.append(line + '\n')
To read multiple lines from a file, it's easiest to use readlines(), which will return a list of all lines in the file. To read the file use:
with open(directory, 'r') as f:
lines = f.readlines()
And to write out your changes, use:
with open(directory, 'w') as f:
f.writelines(lines)
fileList = [line for line in open("file.txt")]
While the previously mention idiom will work for reading files, I like mine. Its short and to the point.