Reputation:
So im trying to write a program that encrypts a word document and decrypts it in another. Im able to get the program to work if i put the key into the program but i want to have it to read the key from key.txt. I keep getting an error (AttributeError: 'str' object has no attribute 'items') when i put the key in the program. Any help is appreciated. Thanks
This is what the key file contains {'A':'6', 'a':'~', 'B':'66', 'b':';', 'C':'<', 'c':'@', 'D':'%$', 'd':'#', \ 'E':'5', 'e':'$', 'F':'3', 'f':'%', 'G':'71', 'g':'^', 'H':'72', 'h':'&', 'I':'4', 'i':'*', \ 'J':'74', 'j':'(', 'K':'75', 'k':')', 'L':'1', 'l':'_', 'M':'77', 'm':'`', 'N':'/:', \ 'n':'-', 'O':'79', 'o':'+', 'P':'2', 'p':'=', 'Q':'99', 'q':'9', 'R':'82', 'r':'>', 'S':'83', \ 's':'[','T':'', 't':']', 'U': ';', 'u':'{', 'V':'86', 'v':'}', 'W':'7', 'w':'/', \ 'X':'/+', 'x':'8', 'Y':'%(', 'y':'0', 'Z':'90', 'z':'$122'}
Heres the encryption
def main():
codes = open('key.txt', 'r')
code = codes.read()
inputfile = open('text.txt', 'r')
paragraph = inputfile.read()
inputfile.close()
encrypt = open('Encrypted_File.txt', 'w')
for ch in paragraph:
if ch in code:
encrypt.write(code[ch])
else:
encrypt.write(ch)
encrypt.close()
main()
Heres the decryption
def main():
codes = open('key.txt', 'r')
code = codes.read()
inputfile = open('Encrypted_File.txt', 'r')
encrypt = inputfile.read()
inputfile.close()
code_items = code.items()
for ch in encrypt:
if not ch in code.values():
print(ch, end='')
else:
for k,v in code_items:
if ch == v:
print(k, end='')
main()
Upvotes: 0
Views: 2927
Reputation: 36033
code = codes.read()
At this point code
is a string, which is always the case when a file is read. Python does not automatically figure out what to convert it to, especially since a file can contain literally anything. To convert to a dictionary:
from ast import literal_eval
code = literal_eval(codes.read())
Upvotes: 2