MST
星途 面试题库

面试题:Python如何安全读取用户生成的大文本数据并处理

假设用户会输入一个非常大的文本文件数据,需要逐行读取并对每行数据进行特定的加密处理(例如简单的凯撒密码加密,偏移量由用户输入指定),请设计一个Python程序实现该功能,要考虑内存优化和异常处理。
27.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def caesar_encrypt(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            if char.isupper():
                result += chr((ord(char) - 65 + shift) % 26 + 65)
            else:
                result += chr((ord(char) - 97 + shift) % 26 + 97)
        else:
            result += char
    return result


def process_large_file(file_path, shift):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                encrypted_line = caesar_encrypt(line.strip(), shift)
                print(encrypted_line)
    except FileNotFoundError:
        print(f"文件 '{file_path}' 未找到。")
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    file_path = input("请输入文件路径: ")
    try:
        shift = int(input("请输入凯撒密码偏移量: "))
        process_large_file(file_path, shift)
    except ValueError:
        print("偏移量必须是一个整数。")