简体   繁体   English

拒绝在python中读取文件的一部分

[英]Deny reading part of a file in python

I have a text file for which I use two write functions: 1) Normal Write, 2) Secure Write. 我有一个使用两个写入功能的文本文件:1)普通写入,2)安全写入。

Now when I want to read the data from the file, I should be only be able to read the data written using the "Normal Write" function and should not be able to read the data written using "Secure Write" function. 现在,当我想从文件中读取数据时,我应该只能读取使用“正常写入”功能写入的数据,而不能读取使用“安全写入”功能写入的数据。

My idea was to use a dictionary for this using the key as a flag to check if the value was written using normal write or secure write. 我的想法是为此使用字典,并使用密钥作为标志来检查该值是使用普通写入还是安全写入写入的。

How can I do this in Python? 如何在Python中执行此操作?

its all a matter of how secure you want your data. 这完全取决于您想要数据的安全性。 the best solution is to use encryption, or multiple files, or both. 最好的解决方案是使用加密,或使用多个文件,或同时使用两者。

if you simply want a flag that your program can use to tell if data in a file is normal or secure, there are a few ways you can do it. 如果您只是想要一个标志,程序可以使用该标志来判断文件中的数据是正常还是安全,则有几种方法可以使用。

  • you can either add a header each time you write. 您可以在每次写入时添加标题。
  • you can start each line with a flag indicating secure level, and then read only the lines with the correct flag. 您可以以指示安全级别的标志开始每行,然后仅读取具有正确标志的行。
  • you can have a header for the whole file indicating the parts of the file that are secure and those that aren't. 您可以在整个文件的标头中指出文件中哪些部分是安全的,哪些部分不是安全的。

here is a way i would implement it using the first option. 这是我将使用第一个选项实现它的方法。

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)

this should work. 这应该工作。 but its not the best way to secure your data. 但这不是保护数据的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM