0

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()
3
  • 2
    A friendly reminder, don't use open and close. Instead use with open('filename') as file:. This will automatically close the file when your program crashes before the call to close to prevent memory leaks. Commented Nov 10, 2016 at 21:58
  • @sobek Great ill try to use that. Thanks for the tip. Commented Nov 10, 2016 at 22:04
  • I worded that strangely. :-) If you use with open(), you don't need to use close. Just to remove the ambiguity from my statement. Commented Nov 10, 2016 at 22:08

1 Answer 1

2
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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.