Issue
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')
Solution
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 the files
array that os.walk
returns is just the names of the files at that level, and so you need to combine it with the root
value to get the full path.
Rewriting your code to use that renders:
from cryptography.fernet import Fernet
import os
import path
'''
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()))
for root, dirs, files in os.walk('.'):
print(files)
for filename in files:
filepath = path.join(root, filename)
with open(filepath, 'rb') as f:
data = f.read()
with open(filepath, 'w') as f:
print(len(data))
f.write(fer.encrypt(data).decode())
print('done')
Answered By - MasterOdin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.