Python文件加密代码异常求助:输出全为'wwww'问题排查
问题排查与代码修正
Hey there! Let's break down why your encryption code is only outputting 'wwww' and fix it step by step:
1. 核心问题:遍历行而非单个字符
你用了sequence = infile.readlines(),这会把文件的每一行作为一个元素存入列表。当你循环for character in sequence时,character其实是一整行文本,而不是单个字符。alphabet.find(character)自然找不到这个整行字符串,返回-1。此时shiftedAlphabet[-1]会被取到(Python允许负索引,-1表示最后一个元素),所以每一行都会输出同一个字符(也就是你看到的'w')。
解决办法:用infile.read()读取整个文件的所有内容为一个字符串,这样就能遍历每个单个字符了:
sequence = infile.read()
2. 处理不在字母表中的字符
如果输入文本里有alphabet中没有的字符(比如换行符、特殊符号),alphabet.find()会返回-1,同样会取到shiftedAlphabet[-1]。你可以选择保留原字符,避免错误输出:
if letterIndex != -1: encryptedCharacter = shiftedAlphabet[letterIndex] else: encryptedCharacter = character # 保留不在字母表中的原字符
3. 文件资源的正确管理
你的代码没有手动关闭文件,可能导致资源泄漏。推荐使用with语句,它会自动帮你完成文件的关闭操作:
with open(inputFileName, "r") as infile, open(outputFileName, "w") as outfile: # 读取和写入操作放在这里
修正后的完整代码
inputFileName = input("Enter the input file name: ") # 修正了原提示的错误,应该输入文件名而非消息 key = int(input("Enter the shift key: ")) outputFileName = input("Enter the output file name: ") alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" shiftedAlphabetStart = alphabet[len(alphabet) - key:] shiftedAlphabetEnd = alphabet[:len(alphabet) - key] shiftedAlphabet = shiftedAlphabetStart + shiftedAlphabetEnd print(alphabet) print(shiftedAlphabet) encryptedMessage = '' with open(inputFileName, "r") as infile: sequence = infile.read() # 读取整个文件内容为字符串 for character in sequence: letterIndex = alphabet.find(character) if letterIndex != -1: encryptedCharacter = shiftedAlphabet[letterIndex] else: encryptedCharacter = character # 保留不在字母表中的字符 encryptedMessage += encryptedCharacter print(f"The encrypted message is: {encryptedMessage}") # 写入加密后的内容到输出文件 with open(outputFileName, "w") as outfile: outfile.write(encryptedMessage)
另外,我修正了原代码里的输入提示错误——原来的提示是让用户输入加密消息,但实际应该输入文件名,这个小失误也可能导致你测试时的混淆。现在用修正后的代码,搭配你提供的输入文本和对应密钥,就能得到符合预期的加密结果啦!
内容的提问来源于stack exchange,提问作者Lethal_bacon
相关产品推荐
相关产品推荐

