Reputation: 25
My sample text file is: 'abcd abcd abcd'
The program has a dictionary with symbols dedicated for each letter. The objective is to create a new file with the files message encrypted.
Program 'works'. By this I mean that it only converts abc. Since theres no d in the dictionary then it raises an error. I removed the d and tried again, but this raises another error called: KeyError: ' '
How can I make my program detect spaces, and write the letter even if theres no symbol for it?
def main():
ecrypt = {'a':'%', 'b':'&', 'c':'/'}
input_file = open('efile.txt', 'r')
output_file = open('newefile.txt', 'w')
line = input_file.readline()
for letter in line:
if letter in line:
output_file.write(ecrypt[letter])
main()
Upvotes: 2
Views: 287
Reputation: 107287
You can use a try-except
for handle the KeyError
but as a more pythonic way you can use str.translate()
function that is actually for this aim :
>>> from string import maketrans
>>> i='abc'
>>> o='%&/'
>>> trantab = maketrans(i, o)
>>> print 'abcd abcd abcd'.translate(trantab)
%&/d %&/d %&/d
and for translate the file and write in another file :
from string import maketrans
i='abc'
o='%&/'
trantab = maketrans(i, o)
with open('efile.txt', 'r') as infile,open('newefile.txt', 'w') as out :
out.write(infile.read().translate(trantab))
Upvotes: 5
Reputation: 21563
You're trying to access ecrypt['d'] which doesn't exist. With this current code, you'd need to make sure every character (not just letter, punctuation... Spaces...) is in the ecrypt dict.
I suggest adding an exception. See https://docs.python.org/2/tutorial/errors.html The 'if letter in line' is superfluous.
for letter in line:
try:
output_file.write(ecrypt[letter])
except KeyError:
output_file.write(letter)
Or, test that the letter exists first.
for letter in line:
cipher_letter=ecrypt[letter] if letter in ecrypt else letter
output_file.write(cipher_letter)
Upvotes: 3