Reputation: 19
Make a Cryptography program as follows.(Add file i/o to it)
Here are the codes I need to add in the program:
#open file to write record(s). It will create the file if new!
f = open("temp.txt", "w")
f.write("Hello!\n")
f.close
#open file to read this time
f = open("temp.txt", "r")
line = f.readline()
print(line)
f.close
#try binary read...
f = open("temp.txt", "rb")
line = f.readlines()
print(line)
f.close
Here is what I have already (Everything but the input/output functions for the files):
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
mode = input("Do you wish to encrypt or decrypt a message?").lower()
if mode in "encrypt e decrypt d". split():
return mode
else:
## print("Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
return input("Enter you message")
def getKey():
key = 0
while True
key = int(input("Enter a key number (1-26)"))
if (key >=1 and key <= MAX_KEY_SIZE):
return key
def getTranslatatedMessage(mode, messafe, key):
if mode[0] == "d":
key = -key
translated = ""
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupport():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
elif symbol.islower():
if num < ord("z"):
num += 26
elif num < ord("a"):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
My question is where do I add the above codes into the encrypt/decrypt program?
Upvotes: 0
Views: 1035
Reputation: 15328
It seems you want to proceed a file instead of a message provided by the user. So in getMessage you should return the content of the read file
def getMessage():
f = open("temp.txt", "r")
text = f.read()
f.close()
return text
And you write to file the translated message.
Upvotes: 0
Reputation: 15328
You didn't ask your question.
You can find informations about input/output in Python documentation
Basically, you can open a file, write into it and close it as following:
f = open("myfile", "w")
text = "something"
f.write(text)
f.close()
To deal with binary data it is possible to specify binary format "wb" for writing or "rb" for reading and conversions like:
f = open("binfile", "rb")
buffer = f.read(2)
print hex(ord(buffer[0]))
There are other ways to pack/unpack binary files in Python but you must ask a more precise question.
Upvotes: 0