Python file scanning - python

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()

Related

Changing the string value that uses return file.name after creating name file

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()

Why is my user input not called when I run this function?

I'm super new to python and am working on a project for school. I am trying to open up a csv file to use in later functions. When I run my code, my terminal does not prompt me for an input at all. What am I missing? This works if I just remove the "def get_input_descriptor" but my project requires that I define this as a function.
def main():
def get_input_descriptor():
while True:
filename= input("Enter a file name: ")
try:
file = open(filename,newline = '')
break
except IOError:
print("Bad file name, try again")
continue
def get_data_list(filename):
filedata = csv.DictReader(file)
column = input("Which Column: ")
if column == 1:
columnread = "Open"
elif column == 2:
columnread = "High"
elif column == 3:
columnread = "Low"
elif column == 4:
columnread = "Close"
elif column == 5:
columnread = "Volume"
elif columnread == 6:
columnread = "Adj Close"
datalist = []
for row in filedata:
print(row["Date"],row[columnread])
main()
You should probably read this page first before asking homework related questions How do I ask and answer homework questions?
However... In Python defining a function with def will only run that code if the function gets called e.g. get_input_descriptor() When you remove the def get_input_descriptor(): bit the code is no longer "locked" in a function and is now part of the main method an so can run.
If you NEED to make this a separate function then you would move it above the main method code and then call the function get_input_descriptor() from within the main method
You are not actually making a call to the get_data_list function.
When you use the def keyword in python, that means you are defining a function that you later wish to call. So you're just setting it up so you can use it later.
You've already done this with the main function, you use def main(): at the start, which sets it up, then later you call main() to actually run the function.
So what you're doing here is setting up a function called main, then you call that function later. When you call it, it sets up two more functions get_input_descriptor and get_data_list, but neither of them actually get called. I'm guessing, but you probably want something that looks more like this
def get_input_descriptor():
while True:
filename= input("Enter a file name: ")
try:
file = open(filename,newline = '')
break
except IOError:
print("Bad file name, try again")
continue
def get_data_list(filename):
filedata = csv.DictReader(file)
column = input("Which Column: ")
if column == 1:
columnread = "Open"
elif column == 2:
columnread = "High"
elif column == 3:
columnread = "Low"
elif column == 4:
columnread = "Close"
elif column == 5:
columnread = "Volume"
elif columnread == 6:
columnread = "Adj Close"
datalist = []
for row in filedata:
print(row["Date"],row[columnread])
def main():
get_input_descriptor()
get_data_list(filename)
main()
There are a few other problems in your code, but I think you can work them out if you get passed this problem.

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')

Python, Writing the file twice

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.

Anything other than the variable Python

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()

Categories