I am very much new to Python and basically want anything other than d or o to rerun the question? Any help?
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
if Myfile == 'd':
print 'default choosen '
Myfile = 'M:/test/testchains_a.csv'
if Myfile == 'o':
print 'own file choosen '
Myfile = raw_input('Enter absolute path to the .csv file:')
else:
print 'successful'
You could use a while loop to check whether or not the input is and 'o' or a 'd':
MyFile = None
while MyFile != 'o' and MyFile != 'd':
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
You can do this the way squiguy suggested, but it might be more readable to put the whole thing into a loop, so you don't have to repeat the same checks twice:
while True:
Myfile = raw_input( '''Specify filename (o) or use default chain (d)? ''')
if Myfile == 'd':
print 'default choosen '
Myfile = 'M:/test/testchains_a.csv'
break
elif Myfile == 'o':
print 'own file choosen '
Myfile = raw_input('Enter absolute path to the .csv file:')
break
This will loop forever, until it hits a breakāin other words, until they select 'd' or 'o'.
You can use a loop:
wrong = True
while(wrong):
file = raw_input("My awesome prompt")
if file == "d":
file = '/some/path'
wrong = False
if file == "o":
file = raw_input("Where?")
wrong = False
# Continue your program...
I think your actual problem here is bad UI design. The first question is superfluous and can be easily eliminated:
myfile = raw_input('Enter absolute path to the .csv file (leave blank to use the default):')
myfile = myfile or 'M:/test/testchains_a.csv'
This "hit enter to use the default" approach is quite common in dialogue programs.
To answer the question as asked, I'd suggest using a function like this:
def prompt(message, choices):
while True:
s = raw_input(message)
if s in choices:
return s
and in your main code:
option = prompt('Specify filename (o) or use default chain (d)? ', 'od')
if option == 'd':
...
elif option == 'o':
...
use elif (elseif) and else
file = input("enter (d) to use the default file or enter (c) to specify a custom path: ")
if file.lower() == "d":
print("some code")
elif file.lower() == "c":
print("some code")
else:
print("invalid answer!")
input()
Related
I'm really new to Python. Only one week of study so please I know this is not the best possible way of doing things but I'm trying. So I have this memo "muistio.txt"and after program checks if it already exists or not you can make some simple inputs.
Everything works okay but after Choice 4 I want to change part print("You're at currently",name) for the file name that was created and using it until new one is created or program is closed.
How do I achieve this?
import time
def finding_file():
try:
file = open("muistio.txt", "r")
return file.name
except IOError:
file = open("note.txt", "w")
print("Can't find the file, creating.")
filename = file.name
return filename
def new_memo():
memo = input("Give name: ")
try:
memo = open(memo, "r")
print("Using memo: " + memo.name)
memoname = memo.name
return memoname
except IOError:
memo = open(memo, "w")
print("Memo not found, creating")
memoname = memo.name
return memoname
def main():
while True:
name = finding_file(),new_memo()
print("You're at currently", name)
print("(1) Read\n(2) Add\n(3) Empty\n(4)Change\n(5) Quit")
choice = int(input("What you want to do?: "))
if choice == 1:
memo = open("muistio.txt", "r")
inside = memo.read()
print(inside)
memo.close()
elif choice == 2:
memo = open("muistio.txt", "a")
writing = input("Write new note: ")
timestamp = time.strftime("%X %x")
memo.write(writing+":::"+timestamp)
memo.close()
elif choice == 3:
memo = open("muistio.txt", "w")
memo.truncate(0)
print("Memo empty.")
memo.close()
elif choice == 4:
new_memo()
elif choice == 5:
print("Quitting.")
break
if __name__ == "__main__":
main()
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')
I'm trying to get my code so it will update Y7,Set1.txt but it keeps writing the data inside it again, + my new data that was added.
My code below:
print("Registration System")
print("Make sure their is atleast one name in register!")
password = ("admin")
check = input("The Administration Password is: ")
if check == password:
input("Enter any key to continue ")
print("If their is no names in the register.txt\nThe script will stop working here!")
set1 = list()
set2 = list()
set3 = list()
set4 = list()
set5 = list()
with open("register.txt", "r") as register:
registers = [line.rstrip("\n") for line in register]
for pop in registers:
print(pop)
choice = input(
'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
if choice == '1':
set1.append(pop)
elif choice == '2':
set2.append(pop)
elif choice == '3':
set3.append(pop)
elif choice == '4':
set4.append(pop)
elif choice == '5':
set5.append(pop)
with open("Y7,Set2.txt", "r") as Y7R:
Y7 = [line.rstrip("\n") for line in Y7R]
with open("Y7,Set2.txt", "w") as Y7Y:
data = (str(Y7) + str(set2))
Y7Y.writelines(data)
with open("Y7,Set1.txt", "r") as d:
Y7S = [line.rstrip("\n") for line in d]
with open("Y7,Set1.txt", "w") as Y7D:
data2 = str(Y7S) + str(set1)
Y7D.writelines(data2)
else:
print("Access Denied!")
However the text file keeps printing the previous values, + a lot of ///////
Anyway I can get my code just to add information to that file, without adding all the /// and previous names? Thanks!
What's happening in the file is:
['[\'[\\\'[\\\\\\\'[\\\\\\\\\\\\\\\'[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'[\\\\\\\
PaulBrennan\\\\\\\\\
Open the file with "a" mode. "r" mode is used when the file only needs to be read and "w" for only writing (an existing file with the same name will be erased).
open("Y7,Set2.txt", "a")
You can check the docs.
I have a some code in a game I'm making where it stores user data on a text file called data.txt. The following code is when a person continues, then it will read the part where the level is stored and see where it will begin the game:
elif choice==("2"):
contusername = input("Enter the name you registered with")
with open("data.txt") as f:
f.readline()
for lines in f:
name, level = lines.split()
if name == contusername:
userdata = level
break
while True:
if level == 1:
level1()
elif level == 2:
level2()
#and so on
But it won't work. Python can't read the text file. How do I fix this?
You probably forgot to cast to int:
userdata = int(level)
Other way your userdata are strings of form '1\n'
Also, you want to use this userdata in comparison, not level
while True:
if userdata == 1:
level1()
p.s. I don't know whether this while True: statement is correct, as only a code excerpt is presented, but it also looks suspitious for me.
It appears you have a Type problem. Reading from a file will give you a string, but you are checking for integers.
Try forcing the level numbers to an int.
elif choice==("2"):
contusername = input("Enter the name you registered with")
with open("data.txt") as f:
f.readline()
for lines in f:
name, level = lines.split()
if name == contusername:
userdata = level
break
level = int(level) # <-- force the level to an integer
while True:
if level == 1:
level1()
elif level == 2:
level2()
This should work :
elif choice == "2":
contusername = raw_input("Enter the name you registered with")
with open("data.txt") as f:
for lines in f.readlines():
name, level = lines.split()
if name == contusername:
userdata = int(level)
break
while True:
if userdata == 1:
level1()
elif userdata == 2:
level2()
How do I make it where if the user enters 'no' the program won't go through the for loop either. I don't want it to tmpfile.write(line) if the user enters 'no'.
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
break # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Set a flag variable and then break out of the while loop. Then in the for loop, check if the flag is set, and then break.
PS: if is not a loop
The easiest way to do this is to create a function that gets user input:
def get_yes_or_no(message):
while True:
user_in = raw_input(message).lower()
if user_in in ("yes", "no"):
return user_in
And modify your original function like so:
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
answer = get_yes_or_no('Are you sure you want to remove ' + line.upper() + '?')
#answer logic goes here
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Python has exceptions, which you can use in place of a GOTO type of construction.
class Breakout(Exception):
pass
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
try:
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
raise Breakout()
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
except Breakout:
pass
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Notice where in exception is raised in the middle there.
You have to put the whole for loop in a function and use return to get out of it:
def find_and_remove(f,coname,tmpfile):
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
return # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
find_and_remove(f,coname,tmpfile)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Instead of using an infinite loop and breaking when you skip a line, differentiate between the three cases (skip, remove, and invalid answer) using a flag in the loop condition. You set the flag to exit the loop in the skip case, break in the remove case, and leave the flag as-is in the invalid answer case. This lets you use the else clause of the while (which is triggered if the while exits because the condition became false) to detect the skip case. From there, you can jump ahead to the next iteration of the for loop using continue (or skip all the rest of the lines using break - it isn't quite clear from the question which you intend, but the difference is change of keyword):
for line in f:
if coname.upper() in line:
answered = False
while not answered:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
break
elif answer == 'no':
answered = True # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
continue
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'