拒绝在python中读取文件的一部分 [英] Deny reading part of a file in python

查看:210
本文介绍了拒绝在python中读取文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我怎么能在Python中这样做?

How can I do this in 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.


  • 你可以在每次写作时添加标题。

  • 你可以用一个表示安全级别的标志开始每一行,然后只读取带有正确标志的行。

  • 你可以有一个整个文件的标题,表示文件的安全部分和非安全部分。

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

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.

这篇关于拒绝在python中读取文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆