Is it possible to have questions and answers exported to a text file such as result.txt?
I answer all the questions and at the end - all the information is saved in a txt file as a list, that can be viewed later.
Example:
Question 1
Answer 1
Question 2
Answer 2
...
I was wondering about file=open, but would that be right?
And how do I export input questions with file open?
I hope you can help.
from datetime import date
today = date.today()
date = today.strftime("%d.may, %Y.year\n")
print("Today is:", date)
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
while True:
name = input("Let's see!\nWhat is your name? ")
description = input("Enter a description of the environmental pollution: ")
city = input("In which city is environmental pollution observed? ")
address = input("Enter your residential address: ")
try:
question = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n" ))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if question == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif question == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
As you wanted the file content as a key-value pair, initialize a dictionary and add the corresponding values, instead of using separate variables for names, descriptions, etc. use them as dictionary keys.
First, initialize a global dictionary
global mydict
Initialize it in Vide() function. (use of global keyword because mydict is being modified in a function)
global mydict
mydict = {}
Store question and answer as a key-value pair
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
In try block:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
Now the if-else statements:
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
After calling the function Vide(), write your dictionary to a file
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
Whole code
global mydict
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
global mydict
mydict = {}
while True:
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
try:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
This can be done by writing or appending to a text file. You are correct, we can use the file = open structure to achieve this. I suggest writing something like the following:
file = open('results.txt', 'w')
Then use the following to write to the file once it has been opened.
file.write("Use your variables and questions from before to print user entered data")
Don't forget to close the file once you're done!
file.close()
Related
The following code randomly stops where mentioned in the code.
def playSaved(choiceSaved):
y = open(choiceSaved,'r')
for line in y.readlines():
qna = line.split(" : ")
randQues.append(qna[0])
randAns.append(qna[1])
print("Processing game.....")
time.sleep(2)
savedChoice = input("\nOk! Are you ready to play? (Y/N) ")
# the code stops here, after getting the input
if savedChoice.lower() == 'y':
for num in range(len(y.readlines())):
count = 1
if "?" in randQues[num]:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
else:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
if ansForSaved == randAns[num]:
print("Correct!")
else:
print("Wrong!")
I tried looking online, but didn't find anything. I figured i could ask here
it reads the line from a text file and the first part is a question the second part is the answer i want to check if the answer input by user matches the answer based on the txt file
some sample data:
name : jd
country : finland
age : 23
colour: red
The for loop:
for num in range(len(y.readlines()))
...will never be entered because the file contents have already been consumed.
Change to:
for num in range(len(randQues))
Hello everyone so I have an issue trying to find the user input in a dictionary.
My function is getting data from a website and writing it to a text file. Then transferred into a dictionary, from there I will ask the user to input a country name and it will return the key and the value of that key or the capita income. The issue i am having is that i have to search the dictionary to find the input and if it matches the key then it will print that and the capita income. Im not 100 percent sure what to use if i should use a for function or if my code is correct at the end.
def main():
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile) #connects to the file and gest a response object
with open("capital.txt",'wb') as f:
f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
f.close()
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num,*key,value = line.split()
key = ' '.join(key)
countryName[key] = value.upper()
userInput = input("Enter a country name: ")
userInput.upper()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
while(userInput != 'stop'):
#for loop to see if key is in dictionary
if userInput in countryName:
#if(userInput == countryName[key]):
print("The per capita income in",key, "is",countryName[key])
userInput = input("Enter a country name: ")
main()
Here is where the issue is, tying to find the if the userInput is the same as the country name key . What would i have to do search the dictionary to match the key to the input, or if there is any uneccesary things in my code.
Update 2
Ah, there was a small issue when comparing the keys. Actually, you were doing upper() on the value (a number) which doesn't make sense.
Have a look at this update:
import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile)
with open("capital.txt",'wb') as f:
f.write(data.content)
countryName = {}
with open('capital.txt','r') as infile:
for line in infile:
num, *key, value = line.split()
key = ' '.join(key)
countryName[key.upper()] = value #key.upper() instead of value.upper()
userInput = input("Enter a country name: ").upper()
counter = 0
while not userInput == "STOP": #'STOP' because it's uppercase
if userInput in countryName:
print("The per capita income in", userInput, "is", countryName[userInput])
userInput = input("Enter a country name: ").upper()
counter += 1
if counter >= len(countryName): #It couldn't find the country
userInput = input("Not found. Enter a new country: ").upper()
counter = 0 #Let's try again
And a small improvement: the counter will prevent the infinite loop when the user input doesn't satisfy the if userInput in countryName and it's not "stop". Besides that, the "stop" condition must be "STOP", once it'll be in upper case.
Hope it helps
Update
As pointed out by #Barmar, another possibility is:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
if userInput in countryName:
print ("The country is", userInput, "and the value is", countryName[userInput])
Just a good advice: I think the file part has nothing to do with your question itself, so, next time try to reduce your problem to, you know, something more direct :)
Anyway, you can loop over the keys of countryName and then compare with the user input. In other words:
countryName = {
"countryA": "valueA",
"countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
for key in countryName.keys():
if userInput == key: #Got it
print ("The country is", key, "and the value is", countryName[key])
Hope it helps
I am a university student and have to prepare a lesson in Python to give to a class of year 9's. I have created an address book program which allows them to create an address book and add entries and view the book.
The one part I can't figure out is how to edit entries. You basically have to be able to pick one out of several lines and then type new data which will save over the original line.
When adding entries originally, I take in the name, age, address and city in separate variables and then write them to a text file with commas between them.
I wasn't sure what information to give over just yet as I don't usually use Stack Overflow so if you need any more information or code please just let me know!
Thank you!
David
Edit I've added all the code below. It prints to a text file and separates them by commas.
def createAddBook():
f = open("address_book.txt", "w")
def viewAddBook():
f = open("address_book.txt", "r")
contacts = f.read()
print(contacts)
print()
f.close
def addEntry():
addList = []
Name = input("What is the name?" + "\n")
Age = input("What is the age?" + "\n")
Address = input("What is the address?" + "\n")
City = input("What is the city?" + "\n")
addList.append(Name + ", ")
addList.append(Age + ", ")
addList.append(Address + ", ")
addList.append(City + "\n")
f = open("address_book.txt", "a")
for entry in addList:
f.write(entry)
f.close()
inuse = True
while inuse == True:
choice = input("Do you have an address book? (yes/no)" + "\n")
if choice == "yes":
choice = input("Would you like to view, add or edit your address book? (view/add/edit)" + "\n")
if choice == "view":
viewAddBook()
elif choice == "edit":
editEntry()
elif choice == "add":
addEntry()
elif choice == "no":
createAddBook()
print("Address book has been created!")
choice = input("Would you like to add an entry to the address book? (yes/no)" + "\n")
if choice == "yes":
addEntry()
elif choice == "no":
inuse = False
elif choice == "close":
break
I understand that you want to create your address book as a CSV file (store one entry per line, and use commas to separate the fields of a given entry). Is that your goal? To manage such a file, the easiest solution is to use the csv module from the standard Python library. Here is a link to the documentation page:
https://docs.python.org/3/library/csv.html#examples
I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.
I am trying to create a quiz where I have questions and answers from an external text file to import into Python so that the user can input a selection.
The problem is that my code only prints "Correct" at the end of the quiz once, and doesn't say after each question answered if the user got the question correct or incorrect.
The first column (detail[0]) is where the question is and the correct answer is in the fourth column (detail[4]))
Thanks
Here is what is in the text file:
What is 1+1,1,2,2
What is 2+2,4,2,4
Here is the source code below:
def quiz():
file = open("quiz.txt","r")
right = False
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
right = True
break
if right == True:
print("Correct")
else:
print("Incorrect")
Just modify the main for-loop to print the result there and then:
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
print("correct!")
else:
print("incorrect :(")