需要帮助用Python制作文件I/O程序

0 投票
2 回答
1033 浏览
提问于 2025-04-18 04:53

制作一个加密程序,具体要求如下:(添加文件输入输出功能)

  1. 你需要有(至少)两个功能:加密和解密。
  2. 增强你的主程序,使其能够: a. 欢迎用户
    b. 询问用户想要加密还是解密
    c. 询问用户要将加密信息写入哪个文件或从哪个文件读取
    d. 如果是加密:
    询问要加密的消息
    询问密钥
    调用加密功能生成密文
    打开文件
    将密文写入文件
    关闭文件
    告知用户密文(显示出来的)已存储到文件中(一定要提到文件名!)
    e. 如果是解密:询问密钥,打开文件,从文件读取密文,关闭文件,调用解密功能解密密文,向用户显示消息
    f. 询问用户是否想执行其他任务
    g. 如果是,返回到(b)
    h. 否则退出

以下是我需要添加到程序中的代码:

#open file to write record(s). It will create the file if new!
f = open("temp.txt", "w") 
f.write("Hello!\n")
f.close

#open file to read this time
f = open("temp.txt", "r")
line = f.readline()
print(line)
f.close

#try binary read...
f = open("temp.txt", "rb")
line = f.readlines()
print(line)
f.close

这是我已经完成的部分(除了文件的输入输出功能):

# Caesar Cipher

MAX_KEY_SIZE = 26

def getMode():
    while True:
        mode = input("Do you wish to encrypt or decrypt a message?").lower()
        if mode in "encrypt e decrypt d". split():
            return mode
        else:
##            print("Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
    return input("Enter you message")

def getKey():
    key = 0
    while True
        key = int(input("Enter a key number (1-26)"))
        if (key >=1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatatedMessage(mode, messafe, key):
    if mode[0] == "d":
        key = -key
    translated = ""

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupport():
                if num > ord("Z"):
                  num -= 26
                elif num < ord("A"):
                  num += 26
            elif symbol.islower():
                if num < ord("z"):
                  num += 26
                elif num < ord("a"):
                  num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated
mode = getMode()
message = getMessage()
key = getKey()

我的问题是,我应该把上面的代码添加到加密/解密程序的哪个地方?

2 个回答

0

你没有问清楚你的问题。

你可以在Python文档中找到关于输入和输出的信息。

简单来说,你可以按照下面的方式打开一个文件,写入内容,然后关闭它:

    f = open("myfile", "w")
    text = "something"
    f.write(text)
    f.close()

如果你要处理二进制数据,可以使用“wb”来写入,或者“rb”来读取,具体的转换方式如下:

    f = open("binfile", "rb")
    buffer = f.read(2)
    print hex(ord(buffer[0]))

在Python中还有其他方法可以打包或解包二进制文件,但你需要问得更具体一些。

0

看起来你想处理一个文件,而不是用户提供的消息。所以在 getMessage 这个地方,你应该返回读取文件的内容。

    def getMessage():
        f = open("temp.txt", "r")
        text = f.read()
        f.close()
        return text

然后你把翻译后的消息写入文件中。

撰写回答