Issue
Good morning. I am trying to create a "for" loop to search for every file with .txt
in a single folder and encrypt them. I was able to successfully do it with a single file but I have been tasked to create a loop to repetitively encrypt multiple files in a single folder
single_encrypt_file.py
from cryptography.fernet import Fernet
file = open('key.key', 'rb')
key = file.read()
file.close()
for filename in os.listdir('testfolder'):
with open(filename, 'rb') as f:
data = f.read()
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
with open(filename, 'wb') as f:
f.write(encrypted)
I am still a beginner in python and programming so it would be great if anyone have ideas on how I should modify my current code. Cheers!
Update: I have modified the code based on the given answer but I am getting an error saying "No such file or directory: testfile.txt" when the file clearly exists when I went to check.
Solution
First thing is to do is to find all the file names in the folder. To do that use os.listdir()
.
Then you simply loop through the filenames:
import os
for filename in os.listdir('dirname'):
##do what you want
Be careful because you might want to check if the folder contains only the files you want to encrypt. Otherwise create an exception to ignore unwanted files
Answered By - DPM
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.