如何在目录中加密嵌套文件夹
我正在尝试制作一个可以加密目录的程序。但是,我目前只能在目录中加密文件,而不得对嵌套的文件夹进行加密。一个例子是,如果您想加密“图片”文件夹,它也将加密“保存的图片”和“相机滚动”以及“图片”中的文件。任何帮助将不胜感激
from cryptography.fernet import Fernet
import os
'''
def write_key():
key = Fernet.generate_key()
with open('key.key', "wb") as key_file:
key_file.write(key)
'''
def load_key():
file = open('key.key', 'rb')
key_ = file.read()
file.close()
return key_
key = load_key()
fer = Fernet(key)
os.chdir(r"C:\Users\{user}\encrypt_test".format(user=os.getlogin()))
files = os.listdir()
print(files)
for i in range(len(files)):
with open(files[i], 'rb') as f:
data = f.read()
with open(files[i], 'w') as f:
print(len(data))
f.write(fer.encrypt(data).decode())
print('done')
I am trying to make a program that can encrypt a directory. What I have currently though, can only encrypt files inside the directory and not encrypt the folders nested. An example would be if you wanted to encrypt the "Pictures" folder, it would also encrypt the "Saved Pictures" and "Camera Roll" along with the files inside "Pictures". Any help would be appreciated
from cryptography.fernet import Fernet
import os
'''
def write_key():
key = Fernet.generate_key()
with open('key.key', "wb") as key_file:
key_file.write(key)
'''
def load_key():
file = open('key.key', 'rb')
key_ = file.read()
file.close()
return key_
key = load_key()
fer = Fernet(key)
os.chdir(r"C:\Users\{user}\encrypt_test".format(user=os.getlogin()))
files = os.listdir()
print(files)
for i in range(len(files)):
with open(files[i], 'rb') as f:
data = f.read()
with open(files[i], 'w') as f:
print(len(data))
f.write(fer.encrypt(data).decode())
print('done')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要做的是递归浏览目录以查找所有文件并对其采取一些操作。 os.listdir 您已经看到的方法只给您是直接目录中的条目。虽然您可以使用该方法编写递归方法(例如检查给定的条目是否是目录,如果是的,则在其上运行
os.listdir
,Else Encrypt,重复),但必须更易于使用 os.walk ,它将处理递归下方的递归对于您来说,以及将文件与每个级别的目录分开。这里要注意的一件事是files
os.walk
返回的数组只是该级别的文件的名称,因此您需要将其与<<代码> root 值以获取完整的路径。重写您的代码以使用该渲染:
What you're asking to do is recursively go through a directory to find all files and apply some action to it. The os.listdir method as you've seen only gives you the entries in the immediate directory. While you could use that method to write a recursive method (e.g. check if a given entry is a directory, if so, run
os.listdir
over it, else encrypt, repeat), it's must easier to use os.walk which will handle the recursion down the file tree for you, as well as separating out the files from directories at each level. The one thing to note here is thefiles
array thatos.walk
returns is just the names of the files at that level, and so you need to combine it with theroot
value to get the full path.Rewriting your code to use that renders: