How to print output to text file from multiple functions (python) - python

I want to save the below code output to file.txt. The problem is that my code includes many functions.
In other words, I want my output in a text file, I'm using python but I posted as js, #python
import random
Generate_Number_CHOICE = 1
Average_Calculate_CHOICE = 2
Display_Grades_CHOICE = 3
Display_Failing_Marks_CHOICE = 4
QUIT_CHOICE = 5
def display_menu():
print(' MENU')
print('1) Enter Your Marks')
print('2) Get Your Average')
print('3) Display Your Grades')
print('4) Display Failin Marks')
print('5) Quit')
def generate_number():
numbers = random.sample(range(1 ,100),30)
print(numbers)
return numbers
def average_calculate(numbers):
total = sum(numbers)
average = total // 30
print('------------------------------------')
print('Your Average is:', average)
print(" ")
def display_grades(numbers):
for mark in(numbers):
if mark >= 90:
print('------------------------------------')
print('A+',mark)
elif mark >= 80:
print('------------------------------------')
print('B+',mark )
elif mark >= 70:
print('------------------------------------')
print('C+',mark)
elif mark >= 60:
print('------------------------------------')
print('D+',mark)
else:
print('------------------------------------')
print('F',mark)
return mark
return courses_Name
def display_failing(numbers):
for number in (numbers):
if number <= 59:
print('------------------------------------')
print("you Fail in",number)
print(" ")
def main():
infile = open('philosophers.txt', 'w')
choice = 0
while choice != QUIT_CHOICE:
display_menu()
choice = int(input('Enter your choice: '))
if choice == Generate_Number_CHOICE:
numbers = generate_number()
elif choice == Average_Calculate_CHOICE:
average_calculate(numbers)
elif choice == Display_Grades_CHOICE:
mark = display_grades(numbers)
elif choice == Display_Failing_Marks_CHOICE:
display_failing(numbers)
elif choice == QUIT_CHOICE:
print('Exiting the program...')
else:
print('Error: invalid selection.')
main()

You can just replace you print statements with infile.write('text goes here'), also don't forget to close your file after you're done with it using infile.close(). Alternately you can use a with statement.
with open('philosophers.txt', 'w') as infile:
infile.write('text')
and this will close the file without explicitly calling .close.
You can also print to a file
print('text', file=infile) #python 3
print >> infile, 'text' #python 2

You can open a file (as global variable) in the beginning of your main function and in all other functions use that file handle to write whatever you want in the file.But an even better solution is to pass that file handle to each function and use the handle to write to file. Either way, don't forget to close the file at the end of the main function.

Related

How to open and read a file in python while it's an subfolder?

I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?
def CreateQuiz(i):
# here i'm creating the keys and values of the "flashcards"
f = open(fileList[i],'r') # using the read function for both files
EngSpanVocab= {} # this converts the lists in the text files to dictionaries
for line in f:
#here this trims the empty lines in the text files
line = line.strip().split(':')
engWord = line[0]
spanWord = line[1].split(',')
EngSpanVocab[engWord] = spanWord
placeList = list(EngSpanVocab.keys())
while True:
num = input('How many words in your quiz? ==>')
try:
num = int(num)
if num <= 0 or num >= 10:
print('Number must be greater than zero and less than or equal to 10')
else:
correct = 0
#this takes the user input
for j in range(num):
val = random.choice(placeList)
spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
if spa in EngSpanVocab[val]:
correct = correct+1
if len(EngSpanVocab[val]) == 1:
#if answers are correct the program returns value
print('Correct. Good work\n')
else:
data = EngSpanVocab[val].copy()
data.remove(spa)
print('Correct. You could also have chosen',*data,'\n')
else:
print('Incorrect, right answer was',*EngSpanVocab[val])
#gives back the user answer as a percentage right out of a 100%
prob = round((correct/num)*100,2)
print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
break
except:
print('You must enter an integer')
def write(wrongDict, targetFile):
# Open
writeFile = open(targetFile, 'w')
# Write entry
for key in wrongDict.keys():
## Key
writeFile.write(key)
writeFile.write(':')
## Value(s)
for value in wrongDict[key]:
# If key has multiple values or user chooses more than 1 word to be quizzed on
if value == wrongDict[key][(len(wrongDict[key])) - 1]:
writeFile.write(value)
else:
writeFile.write('%s,'%value)
writeFile.write('\n')
# Close
writeFile.close()
print ('Incorrect answers written to',targetFile,'.')
def writewrong(wringDict):
#this is for the file that will be written in
string_1= input("Filename (defaults to \'wrong.txt\'):")
if string_1== ' ':
target_file='wrong.txt'
else:
target_file= string_1
# this checs if it already exists and if it does then it overwrites what was on it previously
if os.path.isfile(target)==True:
while True:
string_2=input("File already exists. Overwrite? (Yes or No):")
if string_2== ' ':
write(wrongDict, target_file)
break
else:
over_list=[]
for i in string_1:
if i.isalpha(): ovrList.append(i)
ovr = ''.join(ovrList)
ovr = ovr.lower()
if ovr.isalpha() == True:
#### Evaluate answer
if ovr[0] == 'y':
write(wrongDict, target)
break
elif ovr[0] == 'n':
break
else:
print ('Invalid input.\n')
### If not, create
else:
write(wrongDict, target)
def MainMenu():
## # this is just the standad menu when you first run the program
if len(fileList) == 0:
print('Error! No file found')
else:
print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
print(str(1) ,"Places.txt")
print(str(2) ,"Verbs.txt")
while True:
#this takes the user input given and opens up the right text file depending on what the user wants
MainMenu()
userChoice = input('==> ')
if userChoice == '1':
data = open("places.txt",'r')
CreateQuiz(0)
elif userChoice == '2':
data = open("verbs.txt",'r')
CreateQuiz(1)
elif userChoice == 'Q':
break
else:
print('Choose a Valid Option!!\n')
break
You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script.
Try setting the directory:
import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')

how can I validate a list index as an integer?

I have the code which populates the list "oneStudent" with 5 values, I need to validate indexes 1-4 (so the last 4 values) as an integer. I have tried using try...except, however, no matter how I try to implement it, it breaks the code
I'm relatively new to coding and python, it's probably something small I'm missing, any help will be much appreciated
The idea behind the code is to populate the list oneStudent as many times as NumberOfStduent is input above, after each time the oneStudent list will be appended to allStudent and reset for the next one
in the end, allStudent will be a list containing lists with each oneStudent
while True:
NumberOfStudent = input ("Please input the number of students: ")
try:
NumberOfStudent=int(NumberOfStudent)
if NumberOfStudent in range (1, 6):
break
else:
print("Error, Please input between 1 and 5")
except:
print("Error, Please input a valid number")
print("Number of students:", NumberOfStudent)
allStudents=[]
oneStudent=[]
s=0
while s < NumberOfStudent:
oneStudent.append(input ("Please input student name: ", ))
oneStudent.append(input ("Please mark for the Web module: ", ))
try:
oneStudent[1]=int(oneStudent[1])
if oneStudent[1] > 0 and oneStudent[1] < 101:
pass
else:
print("error1")
except:
print("Error2")
oneStudent.append(input ("Please mark for the Programming module: ", ))
try:
oneStudent[2]=int(oneStudent[1])
if oneStudent[2] > 0 and oneStudent[2] < 101:
pass
else:
print("error1")
except:
print("Error2")
oneStudent.append(input ("Please mark for the Graphics module: ", ))
try:
oneStudent[3]=int(oneStudent[1])
if oneStudent[3] > 0 and oneStudent[3] < 101:
pass
else:
print("error1")
except:
print("Error2")
oneStudent.append(input("Please mark for the Networking module: ", ))
try:
oneStudent[4]=int(oneStudent[1])
if oneStudent[4] > 0 and oneStudent[4] < 101:
pass
else:
print("error1")
except:
print("Error2")
s = s+1
allStudents.append(oneStudent)
oneStudent=[]
if s == NumberOfStudent:
break
print(allStudents)
This should work:
oneStudent=[]
NumberOfStudent = 2
s=0
def validate_number(text):
while True:
try:
question = int(input(text))
if 1 <= question <= 100:
return question
except:
print("That's not a valid option!")
while s < NumberOfStudent:
oneStudent.append(input ("Please input student name: ", ))
web_module = validate_number("Please mark for the Web module: ")
oneStudent.append(web_module)
prog_module = validate_number("Please mark for the Programming module: ")
oneStudent.append(prog_module)
graph_module = validate_number("Please mark for the Graphics module: ")
oneStudent.append(graph_module)
net_module = validate_number("Please mark for the Networking module: ")
oneStudent.append(net_module)
s += 1
print(oneStudent)
allStudents = []
NumberOfStudent = 2
while len(allStudents) < NumberOfStudent:
oneStudent = []
try:
oneStudent.append(input("Please input student name: ",))
oneStudent.append(int(input("Please mark for the Web module: ",)))
oneStudent.append(int(input("Please mark for the Programming module: ",)))
oneStudent.append(int(input("Please mark for the Graphics module: ",)))
oneStudent.append(int(input("Please mark for the Networking module: ",)))
allStudents.append(oneStudent)
except:
print('Enter valid input')
print(allStudents)

How write User Input Data to External Text File?

I would like to be able to take the test scores the user inputs and write to an external text file. Then have the application read off the values from the and calculate the average. However, I am unsure as to how to implement the python syntax within the loop and the functions. I've attempted to utilize my resources to get a better idea of how to do this, but I've been having some trouble understanding how python handles external files. In addition, would using append be better than write in this scenario?
Current Syntax:
def testAvgCalculation():
#Variables
total = 0
total_quiz = 0
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
if inpt.lower()== 'stop':
break
#Data Validation
try:
if int(inpt) in range(1,101):
total += int(inpt)
total_quiz += 1
else:
print("Score too small or Big")
except ValueError:
print("Not a Number")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = testAvgCalculation()
displayAverage(total, total_quiz)
#Run Main Function
main()
This is hacky as heck, but I tried to work with what was already there. I split the data validation section of the original function off into a separate function. In main() it returns its value counter, which keeps track of how many values were entered, to calculate_average(), which then reads the file line by line until counter becomes 0, which means it's about to read the word "stop" (which allows EOF recognition via the 'and' in the if statement), performs the calculation and returns its values.
def write_file():
#Variables
counter = 0
file = open("Scores.txt", "w")
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
file.write(inpt + "\n")
if inpt.lower()== 'stop':
file.close()
break
counter += 1
return counter
def calculate_average(counter):
total = 0
total_quiz = counter
scores = open("Scores.txt", "r")
s = ""
try:
while counter > 0 and s != 'stop':
s = int(scores.readline())
if int(s) in range(1,101):
total += int(s)
counter -= 1
else:
print("Invalid data in file.")
except ValueError:
print("Invalid data found")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = calculate_average(write_file())
displayAverage(total, total_quiz)
#Run Main Function
main()
NOTE: the file is created initially in write mode which overwrites the file each time so you never need a new one. if you want to keep a record you might like to change it to append, though you'll need to manage extracting the proper lines from among old input.
Not pretty at all, but should give you an idea of how to accomplish what you were going for.

completing a function fully

I AM NEW TO PYTHON AND CODING IN GENERAL.
So I have a program with a menu that has multiple functions in it. individually each function works fine on its own, however when i put them together they would usually not fully execute and instead stop half way or wont work at all.
EXAMPLE- the function remove wont remove what i tell it to.
def show_coffee will only show the first description and weight only and nothing else.
What can i do to make the functions fully execute?
import os
def main():
choice =''
fun=[]
while choice != 4:
menu()
choice=getUserChoice()
if choice !=4:
fun=process_choice(choice,fun)
print(fun)
print("Goodby!")
def process_choice(choice,fun):
#fun=fun1
if choice == 0:
fun=add_coffee(fun)
elif choice == 1:
fun=show_coffee(fun)
elif choice == 2:
fun=search_coffee(fun)
elif choice == 3:
fun=modify_coffee(fun)
else:
print(choice,"is not a valid choice.")
return fun
def add_coffee(fun):
another= 'y'
coffee_file=open('coffee.txt', 'a')
Description={}
while another == 'y' or another == 'Y':
print('Enter the following coffee data:')
descr=input('Description: ')
qty= int(input('Quantity (in pounds): '))
coffee_file.write(descr + '\n')
coffee_file.write(str(qty) + '\n')
print("Do you want to add another record?")
another = input("Y=yes, anything else =no: ")
return fun
coffee_file.close()
print('Data append to coffee.txt.')
def show_coffee(fun2):
coffee_file=open ('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != "":
qty= str(coffee_file.readline())
descr=descr.rstrip('\n')
print('Description:', descr)
print('Quantity:', qty)
descr= coffee_file.readline()
fun=fun2
return fun
coffee_file.close()
def search_coffee(fun3):
found=False
search =input('Enter a description to search for: ')
coffee_file=open('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != '':
qty= float(coffee_file.readline())
descr = descr.rstrip('\n')
if descr== search:
print('Description:', descr)
print('Quantity:', qty)
found=True
descr=coffee_file.readline()
fun=fun3
return fun
coffee_file.close()
if not found:
print('That item was not found in the file.')
def modify_coffee(fun4):
found=False
search=input('Which coffee do you want to delete? ')
coffee_file=open('coffee.txt', 'r')
temp_file=open('temp.txt', 'w')
descr=coffee_file.readline()
while descr != '':
qty=float(coffee_file.readline())
descr=descr.rstrip('\n')
if descr !=search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found=True
descr=coffee_file.readline()
fun=fun4
return fun
coffee_file.close()
temp_file.close()
os.remove('coffee.txt')
os.rename('temp.txt', 'coffee.txt')
if found:
print('The file has been update.')
else:
print('The item was not found in the file.')
def menu():
print('''
0. Add or Update an entry
1. Show an entry
2. Search
3. remove
4. Remove number
''')
def getUserChoice():
choice=-1
while choice <0 or choice > 3:
print("Please select 0-3: ",end='')
choice=int(input())
return choice
You are defining functions but this does not call a function. The standard way to do this in Python is use the if __name__=="__main__": statement at the bottom of a file. When the file is executed (instead of functions/classes being imported by another script) the code block within the scope of if __name__=="__main__": is executed.
Get comfortable with this, it's useful and clean :) Good read - What does if __name__ == "__main__": do?
So, for example...
At the bottom of your file...
if __name__=="__main__":
main()

Splitting Array into Strings and Displaying Python

So, I'm trying to take information from bookfile.txt and display information from it. So far, I've opened the file. I'm having trouble getting each line as one object of arrayBooks.
I'd like to have arrayBooks[0]="Animal Farm,1945,152,George Orwell"
Then, I'm going to use book1 = arrayBooks[0].split(',') to split it to other information, such as:
book1[0]="Animal Farm"
book1[1]=1945
book1[2]=152
book1[3]="George Orwell"
So, when I want to find the shortest book, I can compare book1[2] to book2[2] and book3[2] to do so.
My main problem is getting the information in the array and usable. Anything I've tried doesn't seem to work and gives an error in the displayAll() function.
I'm using the displayAll() as a control because I feel if I can get the information to display, I will have it to use.
bookfile.txt:
Animal Farm,1945,152,George Orwell
To Kill A Mockingbird,1960,324,Harper Lee
Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
def main():
print("Welcome!")
displayBookMenu()
populateBooks()
displayAll(populateBooks())
def displayBookMenu:
print("\n1: Display All Books")
print("2: Display Shortest Book")
print("3: Display Longest Book")
print("3: Display Oldest Book")
print("4: Display Newest Book")
print("0: End")
choice = int(input("Choice: "))
if choice == 1:
displayAll()
elif choice == 2:
displayShortest()
elif choice == 3:
displayLongest()
elif choice == 4:
displayOldest()
elif choice == 5:
displayNewest()
elif choice == 0:
exit()
else:
print("Invalid Input")
def populateBooks():
fp = open("bookfile.txt", "r")
return fp.readlines()
def displayAll(arrayBooks):
print ("\nAll Books: \n")
#THIS IS WHERE I GET ERROR vvv
print arrayBooks[0]
def displayShortest():
def displayLongest():
def displayOldest():
def displayNewest():
main()
try this:
lines = [line.strip().split(',') for line in open("books.txt")]
Using list comprehesions you can read your file into a list named lines and convert each line from your files into a list of lists.
These are the results i got when i ran it:
`lines = [line.strip().split(',') for line in open("books.txt")]
print lines
print lines[2]
print lines [2][1]`
enter code here
[['Animal Farm', '1945', '152', 'George Orwell'], ['To Kill A Mockingbird', '1960', '324', 'Harper Lee'], ['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']]
['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']
1813
Now there are a number of edits. Here. Make sure you looks at them carefully:
`def displayBookMenu():
print("\n1: Display All Books")
print("2: Display Shortest Book")
print("3: Display Longest Book")
print("3: Display Oldest Book")
print("4: Display Newest Book")
print("0: End")
choice = int(input("Choice: "))
if choice == 1:
displayAll(populateBooks())
elif choice == 2:
displayShortest()
elif choice == 3:
displayLongest()
elif choice == 4:
displayOldest()
elif choice == 5:
displayNewest()
elif choice == 0:
exit()
else:
print("Invalid Input")
def populateBooks():
lines = [line.strip().split(',') for line in open("books.txt")]
return lines
def displayAll(arrayBooks):
print ("\nAll Books: \n")
#THIS IS WHERE I GET ERROR vvv
for books in arrayBooks:
for each_entry in books:
print each_entry,
print
def displayShortest():
pass
def displayLongest():
pass
def displayOldest():
pass
def displayNewest():
pass
def main():
print("Welcome!")
displayBookMenu()
populateBooks()
main()
Remove displayBooks(populateBooks()) and instead have it in you if choice ==1 statement.
First, you have an error in
def displayBookMenu: #needs ()
And you can't read ArrayBooks because it'a not a global (or nonlocal) variable. I think you have problems with variable scope. Check this: Python variable scope error

Categories