Find the Latest Column From Text File Python - python

I'm working on a project that will allow me to document my earnings/spending's more efficiently, and I cannot seem to find how to find the latest column within a given text file, keep in mind the code is a prototype, as I only started working on it about an hour ago.
f = open('Money.txt','a')
while True:
while True:
OP = input("Operator: ")
if OP == "+" or OP == "-":
break
else:
print("Invalid Operator, please try again.\n\n")
while True:
try:
MA = int(input("Money amount: "))
break
except ValueError:
print("Numeric value only.\n\n")
while True:
if OP == "+":
MV = input("Where you recived the money: ")
break
elif OP == "-":
MV = input("Where you spent the money: ")
break
while True:
C = input('\n\nIs "' + OP + "/" + str(MA) + "/" + MV + '" correct: ')
if C.lower() == "yes":
break
elif C.lower() == "no":
print("Restarting...\n\n")
break
else:
print("Invalid response, try again.\n\n")
if C.lower() == "yes":
break
elif C.lower() == "no":
continue
fs = OP + " $" + str(MA) + " / " + MV
f.write('\n' + fs)
f.close()
print("Values written.")
# "abcde!mdam!dskm".split("/", 2) - basic idea of the code ill use after i figure out how to get latest column from text file
I'm not too great at programming, so if you see a blatant way to improve my code, go ahead and share it, any help will be appriciated!

I figured it out, its probably not the most efficient method but it works:
fc = f.readlines()
l = -1
for line in fc:
l += 1
You can then use "l" to slice your list and do whatever you need to do to it.
Note: You need to change the "f = open('Money2.txt','a')" to "f = open('Money2.txt','r+')"

Related

how can i force to make it to only string

Hello How can i force to make the nname to only string input because even though i put number it still continue to the next function and i only like it to be a name of the people nname= str(input()) does not work thats why im asking if there is other alternative to make it work with only a string
print("Good Day Welcome To our Shop.")
mnu = ["Milktea","Foods", "Drinks", "Dessert"]
lsa = ["1.Matcha", "Taro", "Winter Melon", "Okinawa", "Chocolate",
"Cheese Cake"]
fds = {'Chicken'}
shot = ["tubig"]
mtms = ["ice cream"]
laht = []
print("Hi what would you like to be called, "
"So we can inform you if your order is ready")
def cstmrinfo(name):
print("Okay " + name, "So what would you like to get " )
print(*mnu,sep = "\n")
nname= input().lower()
def kuha_order():
while True:
order = input()
if (order == "Milktea") or (order == "milktea"):
print(lsa)
laht.append(order)
break
elif (order == "Foods") or (order == "foods"):
print(fds)
laht.append(order)
break
elif (order == "Drinks") or (order == "drinks"):
print(shot)
laht.append(order)
break
elif (order == "Dessert") or (order == "dessert"):
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu, "
"Please Try again:")
continue
def pnglhtn():
while True:
print("I Would like to get a: ")
qwe = input()
if qwe in lsa:
print(qwe)
elif qwe in fds:
print(qwe)
elif qwe in shot:
print(qwe)
elif qwe in mtms:
print(qwe)
else:
print("There is no such thing like that ")
continue
dmi = int(input("How Many Servings Would you Like: "))
laht.append(qwe)
laht.append(dmi)
print("So " + pngln, "you Like a " + str(laht[:2]))
print (dmi, "Serves of: " + str(laht[:2]))
break
cstmrinfo(nname)
kuha_order()
pnglhtn()
You can use either lower() or upper(). Please check the following answer:
if order.lower()=="milktea":
print(flvrs)
laht.append(order)
break
OR
if order.upper()=="MILKTEA":
print(flvrs)
laht.append(order)
break
When using the logical "or" operator in an if...else statement in python you have to repeat the variable as well as the value (i know that sounds confusing so look at the example)
this means that this won't work:
if order == "Milktea" or "milktea":
the correct formation should be:
if (order == "Milktea") or (order == "milktea"):
alternatively if you want to simply check one variable against a range of values check out the match...case statements in python 3.10+: https://learnpython.com/blog/python-match-case-statement/
######################################################
Remove the if order in mmu line and indent the corresponding else (code listed below)
def kuha_order():
while True:
order = input()
print(order)
if order == "Milktea":
print(flvrs)
laht.append(order)
break
elif order == "Foods":
print(pgkn)
laht.append(order)
break
elif order == "Drinks":
print(shot)
laht.append(order)
break
elif order == "Dessert":
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu")
continue
you can combine this with my answer above to get what you need :)

How to fix inputting the same character multiple times as a guess?(Beginner Python project - Hangman game)

Inputting the same character multiple times doesn’t work.
Here is my code for the relevant issue
Please be noted that I’ve unnecessarily complicated my code by working on it for a long time to resolve the problem.
I’d really appreciate a correction from anybody.
Thanks in advance
def gamefunction():
global chosenword
global wordlen
global attempts
chosenwordlist = []
tally = 1
print("\nThe word to guess is....\n")
print(chosenword)
display = "_" * len(chosenword)
print(display)
for i in chosenword:
chosenwordlist.append(i)
print(chosenwordlist)
while tally <= int(attempts):
userchoice = input()
guessedletters = []
sameletterguess = []
if len(userchoice.strip()) == 1:
occcurence1 = chosenword.find(userchoice)
if (userchoice in chosenword) and (chosenwordlist.count(userchoice) == 1):
display = display[:occcurence1] + userchoice + display[occcurence1 + 1:]
guessedletters.append(userchoice)
elif (userchoice in chosenword) and (chosenwordlist.count(userchoice) > 1):
sameletterguess.append(userchoice)
display = display[:occcurence1] + userchoice + display[occcurence1 + 1:]
guessedletters.append(userchoice)
print(sameletterguess)
print(sameletterguess.count(userchoice))
if sameletterguess.count(userchoice) == 2:
occurence2 = chosenword.find(userchoice,chosenword.find(userchoice)+1)
display = display[:occurence2] + userchoice + display[occurence2 + 1:]
guessedletters.append(userchoice)
print(sameletterguess)
elif sameletterguess.count(userchoice) == 3:
occurence3 = chosenword.find(userchoice, chosenword.find(userchoice,chosenword.find(userchoice)+1)+1)
display = display[:occurence3] + userchoice + display[occurence3 + 1:]
guessedletters.append(userchoice)
print(sameletterguess)
elif sameletterguess.count(userchoice) == 4:
occurence4 = chosenword.find(userchoice, chosenword.find(userchoice, chosenword.find(userchoice,chosenword.find(userchoice)+1)+1)+1)
display = display[:occurence4] + userchoice + display[occurence4 + 1:]
guessedletters.append(userchoice)
print(sameletterguess)
else:
print("Wrong guess")
tally = tally + 1
print("\n" + display)
if display == chosenword:
tally = int(attempts) + 1
print("Congratulations\nYou guessed the word correctly")
else:
print("Invalid input\nEnter only a single letter\n")
print(display)
For further understanding -
It seems like the code doesn't run through the if-else loop nested within the 'if len(userchoice.strip()) == 1:' loop
One possible solution for your problem is as below.
Extensive comments inside the code.
#Defining globals. Note: Using globals is bad practice, use function arguments instead
chosenword = 'boot'
attempts = 4
def gamefunction():
global chosenword
global attempts
#Create needed extra variables directly from input
wordlen = len(chosenword)
chosenwordlist = list(chosenword)
tally = 1
print("\nThe word to guess is....\n")
print(chosenword)
#Added whitespace for better wordlength visualisation
display = "_ " * wordlen
print(display)
print(chosenwordlist)
#This holds the letters that have been guessed already
guessedletters = []
while tally <= int(attempts):
display = ''
userchoice = input()
if len(userchoice.strip()) == 1:
#check if the guess is part of the word to guess
if userchoice in chosenwordlist:
# Check if letter has been guessed before
if userchoice in guessedletters:
print('You tried that letter already')
continue
else:
# Add the guessed letter to the list of all guessed letters and create display
guessedletters.append(userchoice)
for i in range(wordlen):
if chosenwordlist[i] in guessedletters:
display+=chosenwordlist[i]
else:
display+='_ '
else:
print("Wrong guess")
tally = tally + 1
print("\n" + display)
if display == chosenword:
tally = int(attempts) + 1
print("Congratulations\nYou guessed the word correctly")
else:
print("Invalid input\nEnter only a single letter\n")
print(display)

(Python) ELSE is being executed even when IF has been satisfied?

Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )

Troubleshooting Program in Python. How to link Qs?

I am here to ask another question about the code I am working on. I keep getting invalid syntax error. I asked a similar question on another account and someone answered the question and gave me a code. I edited it but i cannot seem to work it out. My project is to make a troubleshooting program for a mobile company. At the moment this is my code:
CODE:
print("Please answer 'yes' or 'no' to all questions. If you write something else instead of yes or no then your solution might not come out correctly.")
solution = "Keep holding the power on button until the screen is on. If it doesn't turn on, contact your phone provider to get a replacement."
solution2 = "Charge your phone fully and switch it on."
solution3 = "Delete some apps, you need a minimum of at least 5 GB of free memory to run the phone correcly.\nYou are probably out of memory."
sol4 = "Take out everything from the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water."
sol5 = "Reset your phone."
sol6 = "You need a screen replacement. Get it fixed!"
sol7 = "You need to get your buttons replaced!"
sol8 = "Get a screen replacement or contact your phone provider to get a phone replacement."
sol9 = "You need to update your phone software and apps."
sol10 = "You dont need to do anything. Your phone doesnt have any problems."
sol11 = "Please update your phone software."
if input("Did you buy your phone recently? ") == 'yes':
if input("Did your drop your phone? ") == 'yes':
if input("Did it become wet when you dropped it? ") == 'yes':
print(sol4)
else:
print(sol5)
else:
if input("Has your phone ever been to slow?" ) == 'yes':
print(sol5)
else:
if input("Have you got more than 30 apps?? ") == 'yes':
print(solution3)
else:
if input("Is your phone older than two years?") == 'yes':
print(no_warranty)
else:
print(warranty)
else:
print(warranty)
So my question is, how can i complete this code and how can i link questions to more questions?
Thanks!
Invalid Syntax error is because your code is not indented properly.
In python you have to indent the code the right way to make it work since there is no ; in python to end the code line:
e.g for nested code blocks:
{
Block 1
....{
....Block 2
{
....Block 3
}
}
}
Here the 4 dots represent 4 space characters.
for your code you can try like this:
if input("Did you buy your phone recently? ") == 'yes':
if input("Did your drop your phone? ") == 'yes':
if input("Did it become wet when you dropped it? ") == 'yes':
print(sol4)
else:
print(sol5)
....
Always remember, while using python always proprly indent you code otherwise it will throw invalid syntax error.
import time, webbrowser
while True:
print('Hello, welcome to the phone broke hotline. Please follow the questions and only use 1 word answers.')
time.sleep(1.25)#program will stop for 1.25 seconds
print('What phone model do you have?.')
Q1=input().lower() #makes it all lower case
if Q1[0]=='i' or Q1[0]=='s' or Q1[0]=='n' :
if Q1[1]=='p' or Q1[1]=='a' or Q1[1]=='o' :
if Q1[2]=='h' or Q1[2]=='m' or Q1[2]=='k' :
yes='y'
y='yes'
no='n'
n='no'
print('You have chosen ' + '' + Q1+ '' + '')
prob=input('Did your ' + '' + Q1+ '' + ' get wet?\n').lower()
if prob == yes or prob == y:
print("place the phone in a ziplock bag with dry, uncooked rice for a couple of hours and if that doesn't work please contact the nearest phone repair shop")
time.sleep(1)
print()
break
elif prob == no or prob == n:
print('Did your screen crack?')
prob2=input().lower()
if prob2 == yes or prob2 == y:
print ('Go to this link to buy new phone parts.\n https://www.replacebase.co.uk/mobile-phone-parts/')
webbrowser.open('https://www.replacebase.co.uk/mobile-phone-parts/')
time.sleep(1)
print()
break
elif prob2 == no or prob2 == n:
print('Is your ' + '' + Q1+ '' + ' unresponsive?')
prob3a=input().lower()
if prob3a == yes or prob3a == y:
prob3b=input('Is Your ' + '' + Q1+ '' + ' off?\n').lower()
if prob3b == yes or prob3b == y:
print("Turn your " + '' + Q1+ '' + " on and if it wont turn on put it on charge and if that doesn't work contact your nearest phone repair shop")
print()
break
elif prob3b == no or prob3b == n:
print('Go to your nearest phone repair shop')
print()
break
elif prob3a == no or prob3a == n:
print('Has your ' + '' + Q1+ '' + ' overheated')
prob4=input().lower()
if prob4 == yes or prob4 == y:
print('place in a cool area for a couple of hours')
print()
break
elif prob4 == no or prob4 == n:
print('Your ' + '' + Q1+ '' + ' is fine. Thank You for using our services today.')
print()
print(' ...........')
time.sleep(1)
break

Not decrypting what I have encrypted [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having an issue with my decryption algorithm. It outputs to a text file a huge list of repeated ((((( and other things. What's wrong with my code, and how can I fix it? I think it has something to do with the last function of the decrypting process. But I am not sure.
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (evenChars >(oddChars)):
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
for ch in text: #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(ch)
else:
oddNums.append(ch)
index += 1
decrypted= []
if (evenNums >(oddNums)):
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line + "\n"
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
matrices = getMatrices(text)
for value in matrices:
encrypted_file.write(str(value) + "\n")
encrypted_file.close()
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
Well this was a fun one!
in def convertToNum(ch): the alpha does not equal the alpha in def outPutString(text): (missing an *) causing (in my case) tabs instead of spaces and a ? to appear at the end of my decrypted string. I would recommend using a global variable to prevent things like this happening in the future.
Your encryption algorithm worked great and didn't need any adjustment. There were some incompatible variable types in the decryption phase but I managed to get everything to work and have included the working code (my comments marked with ##) I hope this helped.
Edit: As Eric points out in the comments, if (evenNum>(oddNum)) is probably not doing what you want it to do. According to the python docs:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
I Assume you want to compare the lengths of the two arrays to make sure they are equal. If this is the case then you would want to use if (len(evenNum)>len(oddNum))
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
newText = text[0].strip('[ ]') ## these two lines convert the string to an array
textArray = newText.split(',')
for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(int(ch)) ## converting string number to int for later operations
else:
oddNums.append(int(ch))
index += 1
decrypted= []
if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
print(finalString)
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line.
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
##matrices = getMatrices(text)
##for value in matrices:
##encrypted_file.write(str(value) + "\n")
##encrypted_file.close()
## I added the line below(and removed lines above) to be consistent with your later usage
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()

Categories