使用shift加密文件

时间:2014-07-04 15:00:36

标签: python file

不确定我在这里做错了什么?程序要求输入文件名并读取文件,但是当打印出编码的消息时,它会显示为空白。我错过了什么,好像我将短语更改为普通的raw_input(“输入消息”)代码将起作用,但这不是从txt文件读取。

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)

2 个答案:

答案 0 :(得分:1)

这里的问题是这一行的for循环:

for l in phrase:

将返回完整的行,而不是单个字符。

因此,您还必须遍历这些行中的单个字符,或者读取文件二进制文件,或者使用一次读取一个字符的文件对象上的函数。

你可以这样做:

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

答案 1 :(得分:0)

open函数不返回字符串,而是返回打开文件的句柄,从中可以读取字符串。您应该搜索有关如何在Python中将文件读入字符串的信息,然后在REPL中尝试以确保它返回字符串而不是其他内容。