Deny reading part of a file in python

2019-08-04 04:42发布

问题:

I have a text file for which I use two write functions: 1) Normal Write, 2) Secure Write.

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?

回答1:

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.