P_Lee
P_Lee

Reputation: 65

encrypting a file using shift

Not sure what im doing wrong here? the program asks for file name and reads the file but when it come to printing the encoded message it comes up blank. What am I missing, as if I change the phrase to just normal raw_input("enter message") the code will work, but this is not reading from the txt file.

letters = "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
cshift = int(input("Enter a number: "))
phrase = open(raw_input("file name: "), 'r')
newPhrase = ""
for l in phrase:
   if l in letters:
        pos = letters.index(l) + cshift
        if pos > 25:
            pos = pos-26
        newPhrase += letters[pos]

else:
    newPhrase += " "
print(newPhrase)

Upvotes: 0

Views: 74

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391634

The problem here is that the for-loop on this line:

for l in phrase:

will return complete lines, not individual characters.

As such you will have to loop through individual characters from those lines as well, or read the file binary, or use functions on the file object that will read one character at a time.

You could simply do this:

for line in phrase:
    for l in line:
        ... rest of your code here

Upvotes: 1

David Grayson
David Grayson

Reputation: 87506

The open function does not return a string, but a handle to the opened file from which strings can be read. You should search for information on how to read a file into a string in Python and then try it in a REPL to make sure it returns a string and not something else.

Upvotes: 0

Related Questions