I am writing a program to encrypt / decrypt an inputted message using a key generated from a pool
The pool is created by appending unicode characters to an array
When selecting option 2 (encrypt) and reading the genkey.txt file (after generating the key with option 1), the program shows an index error as shown:
Exception has occurred: IndexError
list index out of range, line 58, in b = keyarray[a]
However, when removing the unicode script and replacing the pool with plain text (e.g [a, b, c...]) the message is encrypted without any issue.
Any way to fix this?
Code:
import random
programrun = 0
encryptedarray = []
decryptedarray = []
keyarray = []
while programrun < 1:
pool = []
for i in range(32,123): #Unicode characters
pool.append(chr(i))
print("Encryption / Decryption")
print("")
print("1. Generate Key")
print("2. Encrypt")
print("3. Decrypt")
print("4. Quit")
print("NOTE: Key must be generated before selecting Encryption / Decryption")
print("")
option = int(input("Enter the number corresponding to the option: "))
if option == 1:
a = 20
while a > 0:
b = random.randint(0,57)
c = pool[b]
keyarray.append(c)
a = a - 1
keygen = ("".join(keyarray))
print("Your generated key is:", keygen)
print("")
print("(Make sure you have generated a key before typing 'yes')")
writebool = input("Do you want to save the file to your computer? ")
if writebool == "yes":
keyfile = open("genkey.txt", "x")
keyfile.write(keygen)
keyfile.close()
wbval = 1
print("File saved to genkey.txt successfully")
print("")
quitval = 1
elif writebool == "no":
print("ok")
else:
print("Type yes or no")
elif option == 2:
encryptvalid = 0
while encryptvalid < 1:
msg = str(input("Enter the message to be encrypted: "))
genkeyf = open("genkey.txt", "r")
genkeydata = genkeyf.read()
if genkeydata == keygen:
print("File VALID")
encryptvalid = 1
for i in msg:
a = pool.index(i)
b = keyarray[a]
encryptedarray.append(b)
p = ("".join(encryptedarray))
print("")
print("Your encrypted string is: ")
print("".join(encryptedarray))
else:
print("File INVALID")
print("Please check if the genkey.txt file matches the current generated key.")
a = pool.index(i) looks up the index of a character of the message in the pool, then that index is used to lookup a value in the keyarray with b = keyarray[a].
pool is 91 bytes long, but keyarray is 20 bytes long, so many of the indexes are too high. You probably want b = keyarray[a % len(keyarray)]. This uses the modulus operator to constrain the lookup from 0-19.
Related
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 am trying to write a vigenere cipher code. My psuedo for this is :
- find the index for each letter in plaintext
- find the index for each letter in the key message
- add together the indexes
- new letters will be at the position of the sum of the indexes
I believe I got my code correctly organized but I'm not sure if I'm missing something because I'm getting a type error.
# global constants:
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
ALPHABET_SIZE = len(ALPHABET)
# main function definition:
def main():
# User interface:
print("Welcome to the Vigenere Cipher!")
keep_running = True
while(keep_running):
print("Enter 1 to encrypt a message")
print("Enter 2 to decrypt a message")
print("Enter 0 to exit")
print()
user_choice = int(input("What would you like to do? " ))
if user_choice == 0:
keep_running = False
if user_choice == 1:
plaintext = input("Enter a plaintext message to encrypt: ")
key = str(input("Enter a message to use as the key: "))
ciphertext = enc(key, plaintext)
print("Resulting cipertext:", ciphertext)
print()
if user_choice == 2:
ciphertext = str(input("Enter a ciphertext message to decrypt: "))
key = str(input("Enter a message to use as the key: "))
plaintext = dec(key, ciphertext)
print("Resulting plaintext:", plaintext)
print()
def enc(key, plaintext):
ciphertext = []
for cipher_char in plaintext:
char_pos = ALPHABET.index(cipher_char)
for key_char in key:
message_pos = ALPHABET.index(key_char)
new_pos = (char_pos + key_char)
enc_char = ALPHABET(new_pos)
plaintext += enc_char
return plaintext
# call to main:
main()
The error is at this line
new_pos = (char_pos + key_char)
char_pos is a position and is of type int. key_char is a character and is of type string. You can't add one to the other.
Also in these lines directly above:
for cipher_char in plaintext:
char_pos = ALPHABET.index(cipher_char)
for key_char in key:
message_pos = ALPHABET.index(key_char)
Each of the for loops set the variables (char_pos and message_pos respectively) over and over again. So only the positions of the last character in each string (plaintext and key respectively) in the alphabet are taken into account. So you need to rethink the logic somewhat.
Finally I suggest you include upper case characters in ALPHABET. I got a value error the first time I tried it because I tried upper case input.
I'm writing some python code that works out a person's total pay.
I am able to do this by getting the user to input their pay, however I would like them just to be able to enter their name and then the name is searched in position 0 of a list (Eg. 0,1 0,2 0,2 etc).
I have tried using a tuple but it is not callable and the dictionary and list would not work for me either.
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name:"))
except ValueError:
print("Error")
continue
else:
break
while True:
if name == employeelist[counter,0]:
print(employeelist[counter])
break
valid = 1
elif counter = 3:
print("invalid name")
break
else:
counter = counter + 1
if valid == 1:
break
months = employeelist[counter,1]
pay = employeelist[counter,1]
totalpay = int(months) * int(pay)
Edit:
I do no longer have the code with the dictionary, however I just edited the code from [counter,1] and [0,1] to [counter][1] and is working fine thank you :D
The code below is for your inner loop
employeelist = [["thomas","2","500"], ["jake","1","750"]]
name = ""
while True:
try:
name = input("Name:")
break
except:
print "Error"
position = -1
for i, element in enumerate(employeelist):
if element[0] == name:
position = i
break
if position == -1:
print "Invalid Name"
else:
totalpay = int(employeelist[position][1]) * int(employeelist[position][2])
Your code have multiple bugs. First, valid=1, is set after breaking the loop -meaning valid=1,is never set. You also are checking elif counter = 3 this way, you should rather use two equality signs, like this: elif counter == 3
The error you are getting, that list indices must be integers or slices, not tuple, you are having because you are accessing a multidimensional array the wrong way. Instead of name == employeelist[counter, 0], it should be name == employeelist[counter][0].
Your way of iterating through the array is possible, but its rather simpler using a for loop.
Try this way.
for employees in employeelist:
if name == employees[0]:
print(employee)
valid = 1
break
If it iterated through the hole employeelist, without the if-block running, valid = 1, would never been set.
Working code:
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name: "))
except ValueError:
print("Error")
continue
else:
break
for employees in employeelist:
if name == employees[0]:
print(employees)
valid = 1
break
if valid == 1:
break
months = employeelist[counter][1]
pay = employeelist[counter][2]
totalpay = int(months) * int(pay)
print(totalpay)
I am needing a bit of help on my encryption program. Instead of having the program just move the letters by two (c would become a or r would become p) I'd like to be able to have it reference 2 lists, the first one going from a-z normally and the other with letters in different order to act as the encrypt/decrypt side. Hopefully that makes sense. Here's what i have so far.
result = ''
choice = ''
message = ''
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print(result + '\n\n')
result = ''
if choice == '2':
message = input('\nEnter message to decrypt: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print(result + '\n\n')
result = ''
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
This works fine and dandy but i'd like to have the lists. Lets say list 1 is A,B,C,D,E and list 2 would be W,N,U,D,P. just for ease of use purposes.
Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.
As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.
decrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
result = ''
choice = ''
message = ''
while choice != '0':
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
result = message.translate(encrypt_table)
print(result + '\n\n')
elif choice == '2':
message = input('\nEnter message to decrypt: ')
result = message.translate(decrypt_table)
print(result + '\n\n')
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
Ok, so a few things here...
First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.
Here's the code you're looking for (while retaining the same flow as what you submitted put above):
import random
result = ''
choice = ''
message = ''
characters_in_order = [chr(x) for x in range(32,127)]
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if str(choice) == '1':
message = input('\nEnter message for encryption: ')
r_seed = input('Enter an integer to use as a seed: ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += shuffled_list[characters_in_order.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) == '2':
message = input('\nEnter message to decrypt: ')
r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += characters_in_order[shuffled_list.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) != '0':
print('You have entered an invalid input, please try again. \n\n')
You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.
All of that said...
Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.
Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!
Here is my solution. It uses a randomizer to encrypt the file by assigning a ASCII value to the plain text and randomly shifts it around.
from random import randint
import sys
def menu():
input1=int(input(""" please select what you want to do:
1.Encrypt
2.Decrypt
3.Extended Encryption
4.exit
"""))#menu to choose what you want to do
if input1==1:
encrypt() #takes you to the encrypt function
elif input1==2:
decrypt()#takes you to the decrypt function
elif input1==3:
enxtended()#takes you to the extended encryption function
elif input1==4:
sys.exit #exits the program
else:
print("invalid entry try again")
menu()
def encrypt():
file_name=str(input("please enter the name of the file that you want to open\n"))
try:
text_file=open(file_name + ".txt","r")#puts the text file into read
text_file=text_file.read()#reads the text file
print(text_file)#prints the strings in the document
except:
print("error try again")
encrypt()
random(text_file)
def random(text_file):
list1=("")#creates blank string
for x in range (0,8):
num=(randint(33,126))#generates a random number between33 and 126
ascii1=chr(num) #converts it into an ascii character
list1=list1+ascii1#adds the ascii character to the blank string list1
print (f"your 8 key code is {list1}") #prints 8 character code
offset(list1,text_file)
def offset(list1,text_file):
total=0
for x in range (8,):
total=total+ord(list1[x]) #turns each character into an ascii value
total=total/8 #divides it by
total=round(total,0)#rounds it to 0 decimel places
print(total)
total=total-32#minuses 32 from total
print(f"your offset factor is {total}")
encrypting(total,text_file)
def encrypting(total,text_file):
length=len(text_file)
string1=("")
for x in range (length,):
numascii=ord(text_file[x])#turns the characters into its ascii value
numascii=int(numascii)#makes sure they are integers
if numascii==32:
letter=chr(32)#converts spaces back into spaces
string1=string1+letter#adds space to thestring
else:
numascii1=numascii+total#adds the character value to the offset factor
numascii1=int(numascii1)#makes sure it is an integer
if numascii1>126:# if the ascii value is great then 126
numascii1=numascii1-94#minus 94 from it
letter=chr(numascii1)#turn it into a character
string1=string1+letter#add it to the string
else:
letter=chr(numascii1)#turn the ascii value into a character
string1=string1+letter#add it to the string
print(f"your encrypted file is {string1}")
savefile(string1)
menu()
I have written separate programs for encryption and decryption. Both of these use file manipulation techniques. Use the username 'eggs' and password 'chicks' so that not anyone can see my secret code. I have used hashlib for more security. Just change the User 'Soumajit' to your respective Username to make it work. The first one is encryption and the next one is for decryption.
#ENCRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def en():
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&* ()`-+=1234567890"
encrypt = ""
decrypt = ""
print
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open in desktop: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
print
x = (a.read())
copy2clip(x)
a.close()
print "Right click and select paste below to encrypt"
print
message = raw_input()
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
else:
print "Type your message below"
message = raw_input("")
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
print
a = raw_input("By what name do you want to save it?: ")
file = open(a + ".txt", 'wb')
file.write(e2)
file.close()
copy = raw_input("Do you want to copy your file? ")
if copy == 'y':
copy2clip(e2)
print 'Your encrypted file has been copied to the clipboard'
else:
print "Your encrypted file has been saved with the name " + str(a) + " in desktop"
print "To decrypt it, use my other program"
sleep(3)
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
en()
else:
print "Incorrect username or password"
sleep(1)
#DECRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def de():
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open from folder: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
x = (a.read())
#print x
copy2clip(x)
print "Right click and select paste below to decrypt"
print
message = raw_input()
a.close()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
else:
print "Type or paste your encrypted text below"
print
message = raw_input()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
de()
print
end = raw_input('press q to quit: ')
while end != 'q':
print 'You did not type q'
end = raw_input('press q to quit: ')
if end == 'q':
quit()
else:
print 'Incorrect username or password'
sleep(1)
quit()
I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.
My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.
The records should look like this:
name,score,score,score,score,
etc so they can be split using commas.
I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
EDIT:
Add this function before your "test" function:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
After that, where you have "if users_class == 1:" do this:
writeUserScore("Class1.txt", username, str(correct_answers))
Do the same for the other two else ifs.
Let me know what you think!
Try using a dictionary to hold the existing file data.
Read the file in a variable called "str" for example. And then do something like this:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
When you have a new score you should then do:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
And to save the data back to the file:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
And save the contents of "output" to the file.
PS: If you are not bound by the file format you can use a JSON file. I can tell you more about this if you wish.
Hope that helps,
Alex
First, define these functions:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Now, in the last portion of your code (where you actually write the scores out) becomes much simpler. Here's an example of writing some scores:
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)
there will be two lines in Class1.txt:
phil,7,6,9
alice,6
We read the whole file into a dict (actually a defaultdict(list)),
and overwrite that same file with an updated dict. By using defaultdict(list), we don't have to worry about distinguishing between updating and adding a record.
Note also that we don't need separate if/elif cases to read/write the files. "Scores%d.txt"%users_class gives us the name of the file.