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()
openandclose. Instead usewith open('filename') as file:. This will automatically close the file when your program crashes before the call tocloseto prevent memory leaks.with open(), you don't need to useclose. Just to remove the ambiguity from my statement.