rajiv rai
rajiv rai

Reputation: 1

Taking input from a text file for implementing Caesar Cipher

I am trying to implement Caesar cipher in Python where my program would take input from a text file i.e. input_file.txt, and write the encrypted text as an output to another text file named output_file.txt. The input file contains:

Attack On Titans
4

where "Attack On Titan" is the string to be encrypted and 4 is the key to the encryption algorithm. The correct output for this string should be

Exxego Sr Xmxerw 

but my program gives me

Exxego Sr Xmxerwv

i.e an extra character v. Here is my code for review:

data = open("input_file.txt", "r")
text = data.readline()
print(text)
key = int(data.readline())

def encrypt(text,key):
 result = ""
 for i in range(len(text)):
    char = text[i]
    if char == ' ':
        result += ' '
    elif char.isupper():
        result += chr((ord(char) + key-65) % 26 + 65)
    else:
        result += chr((ord(char) + key - 97) % 26 + 97)
 return result

ex= open("output_file.txt","w")
ex.write(encrypt(text,key))
print(encrypt(text , key))

I just wanted to know why am I getting this incorrect output although I know I can make it correct if I change the for statement by doing this:

for i in range(len(text)-1)

Please don't mind this amateurish coding since I am not good at it and want to improve it. Thanks.

Upvotes: 0

Views: 6062

Answers (3)

NateTheGrate
NateTheGrate

Reputation: 600

It look like you have a trailing newline character in the file you are reading in.

Testing it in the python interpreter:

>>> a = '\n'
>>> (ord(a)+4-97) % 26 + 97
118
>>> chr(118)
'v'

Remove trailing and beginning whitespace by calling test.strip() before passing it to your encrypt function.

As an aside, you should either explicitly close your files, e.g. ex.close() or wrap in in a block like this, to prevent file corruption.

with open('', 'r') as ex:
    ex.write('bar')

Upvotes: 1

Patrick Vanhuyse
Patrick Vanhuyse

Reputation: 41

data.readline() keeps the '\n' (newline) character at the end of the line. It's the reason why you have an extra character in your output.

To remove it you can replace

text = data.readline()

by

text = data.readline().rstrip('\n')

which will remove the '\n' at the end.

text.strip() (see other answers) will remove all whitespace characters from both end of the string. So if it's not the behaviour expected, use .rstrip('\n') which removes only '\n' at the end of the string.

You should also add

ex.close()

after

ex.write(encrypt(text,key))

to commit the change to the file.

Upvotes: 0

Dominic Price
Dominic Price

Reputation: 1146

data.readline() will give you the trailing newline character \n. You need to call text.strip() before passing to the encrypt function to get arid of it.

Upvotes: 1

Related Questions