Python 错误地从 txt 文件中读取

Python incorrectly reading from a txt file

提问人:RedZ 提问时间:11/15/2023 最后编辑:BarmarRedZ 更新时间:11/15/2023 访问量:54

问:

我正在制作一个脚本来使用 caeser 密码加密文件,使用我制作的随机其他脚本作为测试。它正确地写入 txt 文档,密码处于活动状态,但是当我尝试从文件中读取时,它会在应该有一个填充字符的地方添加 €(字母 x 由 8 键组成的密码,到 unicode 索引 128)。

填充字符应该在哪里的 unicode 索引是欧元符号的 3000 以上,重音 A 首先不应该出现,这是我用来运行密码的代码:

def encrypt(file = str, key = int):
    with open(file) as d:
        data = d.read()
    char = []
    for i in data:
        i = ord(i)+key
        i = chr(i)
        char.append(i)
    file = open("encryptedcode.txt","w", encoding = "utf-8")
    for x in char:
        file.write(x)
encrypt("C:/Users/chris/OneDrive/Homework Files/DT/advstrings.py",8)

这是文件 advstrings.py 中的非加密代码:

def advstrings():
    word = input("Please enter a word: ")
    print(word[-1])
    x = len(word)-2
    for i in range(0,len(word)-1):
        print(word[x])
        x = x-1

这是加密文件中显示的内容:

lmn(il\~{|zqvo{01B((((wzl(E(qvx}|0\*Xtmi{m(mv|mz(i(wzlB(\*1((((xzqv|0wzlc59e1(((((E(tmv0wzl15:((((nwz(q(qv(zivom084tmv0wzl1591B((((((((xzqv|0wzlce1(((((((((E(59

这是正确的,但是当我从这个文件中读取,然后将其写入一个新文件时,会出现以下情况:

lmn(il\~{|zqvo{01B((((wzl(E(qvx}|0\*Xtmi{m(mv|mz(i(wzlB(\*1((((xzqv|0wzlc59e1((((€(E(tmv0wzl15:((((nwz(q(qv(zivom084tmv0wzl1591B((((((((xzqv|0wzlc€e1((((((((€(E(€59

这是我用来解密它的方法:

def decrypt():
    newchar = []
    file = open("encryptedcode2.txt","w", encoding = "utf-8")
    with open("C:/Users/chris/OneDrive/Homework Files/DT/encryptedcode.txt") as c:
        chars = c.read()
    for x in chars:
        x = ord(x)-8
        x = chr(x)
        newchar.append(x)
    print(*newchar, sep = "")
decrypt()

最后,这是它在 IDLE 中打印的内容:

def advstrings():
    word = input("Please enter a word: ")
    print(word\[-1\])
    º₤ = len(word)-2
    for i in range(0,len(word)-1):
        print(word\[º₤\])
        º₤ = º₤-1

如果这要读很多,很抱歉,但 python 似乎不喜欢我在 ASCII 的 127 上使用 unicode indeces

Python Unicode

评论

1赞 aw4lly 11/15/2023
我也会把encoding="utf-8"with open(file) as d:
0赞 OM222O 11/15/2023
您的编码和密码都是错误的,将发布带有适当解决方案的答案
0赞 LMC 11/15/2023
无法在 Linux 上重现,因此它可能取决于平台,可能与将文件保存到 OneDrive 有关
1赞 RedZ 11/15/2023
@aw4lly奏效了,谢谢。我还必须放入解密脚本,然后它就修复了。encoding="utf-8"with open(file directory) as c

答:

0赞 OM222O 11/15/2023 #1

我相信您要实现的是扩展版本,但实际的停止密码仅适用于字母字符,而不适用于数字和特殊符号:

from string import ascii_lowercase as lower, ascii_uppercase as upper

# Intended cipher method (encrypts ONLY ALPHABETICAL characters)
def encrypt(string, key=0):
    buffer = []
    lower_offset = ord('a')-key
    upper_offset = ord('A')-key
    for char in string:
        if char.isalpha():
            if char.islower():
                buffer.append(lower[(ord(char)-lower_offset)%26])
            else:
                buffer.append(upper[(ord(char)-upper_offset)%26])
        else:
            buffer.append(char)
    return ''.join(buffer)

# Extending the algorithm to work with any arbitary alphabet
def encrypt_extended(string, key=0, alphabet=[chr(i) for i in range(128)]):
    return ''.join([alphabet[(ord(char)+key)%len(alphabet)] for char in string])

def read_from(file_name):
    with open(file_name, 'r', encoding="UTF-8") as f:
        return f.read()

def write_to(file_name, content):
    with open(file_name, 'w', encoding="UTF-8") as f:
        f.write(content)

        
write_to('hello.txt', 'Hello world!')
original = read_from('hello.txt')
print("Original message is:")
print(original)
encrypted = encrypt(original, 8)
print("Encrypted message is:")
print(encrypted)
write_to('encrypted.txt', encrypted)
decrypted = encrypt(read_from('encrypted.txt'), -8)
print("Decrypted message is:")
print(decrypted)
print(f"Does the decrypted message match the original? {original==decrypted}")