python - 拒绝读取Python文件的部分内容

标签 python security io text-files

我有一个文本文件,我使用两个写入功能:1) 正常写入,2) 安全写入。

现在,当我想从文件中读取数据时,我应该只能读取使用“正常写入”功能写入的数据,而不能读取使用“安全写入”功能写入的数据。

我的想法是使用字典,使用 key 作为标志来检查该值是使用正常写入还是安全写入写入的。

如何在 Python 中执行此操作?

最佳答案

这完全取决于您希望数据的安全程度。最好的解决方案是使用加密或多个文件,或两者兼而有之。

如果您只是想要一个标志,让您的程序可以用来判断文件中的数据是否正常或安全,有几种方法可以做到这一点。

  • 您可以在每次写入时添加标题。
  • 您可以以指示安全级别的标志开始每一行,然后仅读取具有正确标志的行。
  • 您可以为整个文件设置一个 header ,指示文件中安全的部分和不安全的部分。

这是我使用第一个选项实现它的方法。

normal_data = "this is normal data, nothing special"
secure_data = "this is my special secret data!"

def write_to_file(data, secure=False):
    with open("path/to/file", "w") as writer:
        writer.write("[Secure Flag = %s]\n%s\n[Segment Splitter]\n" % (secure, data))

write_to_file(normal_data)
write_to_file(secure_data, True) 

def read_from_file(secure=False):
    results = ""
    with open("path/to/file", "r") as reader:
        segments = reader.read().split("\n[Segment Splitter]\n")
    for segment in segments:
        if "[Secure Flag = %s]" % secure in segment.split("\n", 1)[0]:
            results += segment.split("\n", 1)[0]
    return results

new_normal_data = read_from_file()
new_secure_data = read_from_file(True)

这应该有效。但这并不是保护数据的最佳方式。

关于python - 拒绝读取Python文件的部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12915132/

相关文章:

python - 为什么作为列表的文本表示会消耗如此多的内存?

c++ - 如果我不想让别人知道或更改硬编码值,宏是否比静态常量更安全?

Nuke 中的 Python 多处理导致 Nuke 挂起

Python:将所有函数包装在一个库中

xss - 本地存储和 XSS

c - 从文件中读取配置

haskell - 从 IO Monad 设置配置参数 - 设计模式

java - 在 Java 中 File.canExecute() 究竟做了什么?

python - 扭曲的进程执行问题

android - 防止未经授权访问 Restful API