#copied in from Assignment 2 solution def numericInput(prompt): """Gets user input repeating until they enter a number""" accepted = False while not accepted: text = raw_input(prompt) try: #if the conversion fails, this will error before it returns return float(text) except: print "Please enter a number" def readFile(filename): """reads the lines of a file and returns them in a list""" fileIn = file(filename,"r") lineList = [] for line in fileIn: #remove the newline character if line[-1] == "\n": line = line[:-1] lineList.append(line) fileIn.close() return lineList def writeFile(filename, lines): """write the contents in lines to a file""" fileOut = file(filename,"w") for line in lines: #add the newline character fileOut.write(line + "\n") fileOut.close() return filename = raw_input("Please enter the file you'd like to work with: ") print fileLines = readFile(filename) selection = 0 while selection != 4: if len(fileLines) == 0: print "***The file is empty***" else: lineIndex = 1 for line in fileLines: print str(lineIndex) + "\t" + line lineIndex = lineIndex+1 print print "1. Add a line to the end of the file." print "2. Delete a line from the file." print "3. Insert a line into the file." print "4. Exit, saving changes to the file." print "-----------------------------------------" selection = numericInput("Select an option: ") if selection==1: newLine = raw_input("Enter the new line: ") fileLines.append(newLine) elif selection==2: lineNum = int(numericInput("Which line would you like to delete: ")) try: del fileLines[lineNum-1] except: print "You didn't select a valid line number." elif selection==3: newLine = raw_input("Enter the new line: ") lineNum = numericInput("On which line should it be inserted? ") fileLines.insert(lineNum-1,newLine) elif selection==4: print "Exiting." else: print "Please select a valid option." writeFile(filename,fileLines)