Reputation: 11
Below is my code:
my_text= F = open("mytext.txt")
KEY=4
encoded= ""
for c in my_text:
rem = (ord(c) - 97 + KEY) % 26
encoded += chr(rem + 97)
print(encoded)
Error:
TypeError: ord() expected a character, but string of length 21 found
It returns the error above but I don't know how to solve it.
Upvotes: 1
Views: 48
Reputation: 123423
Iterating over a file retrieves the data line-by-line by default. You can read the file in as a stream of bytes using the two-argument from of the iter(callable, sentinel)
built-in function as shown below. Note this approach will not read the entire file into memory all-at-once like what would happen using something like the readlines()
built-in.
KEY = 4
encoded = ""
with open("mytext.txt", 'rb') as my_text:
# Using iter() like below causes it to quit when read() returns an
# empty char string (which indicates the end of the file has been
# reached).
for c in iter(lambda: my_text.read(1), b''):
rem = (ord(c) - 97 + KEY) % 26
encoded += chr(rem + 97)
print(encoded)
Upvotes: 1
Reputation: 494
you have to use readlines and do other loop for any new line in the text file. otherwise single line will be good.
my_text= F = open("mytext.txt")
my_text = F.readlines()
KEY = 4
encoded= ""
for c in my_text:
for c1 in c:
rem = (ord(c1) - 97 + KEY) % 26
encoded += chr(rem + 97)
print(encoded)
Upvotes: 0