Python File encryption from list

Question:

i am trying to encrypt all files by python script. My goal is to encrypt all files from the target directory including its subdirectories files too. Experts help appreciate. Below my total script.

import os
from cryptography.fernet import Fernet

your_files = []

# os.walk gives us a 3-tuple 
for root, dirs, files in os.walk("E:/test"):
    # go through all the files we found
    for file in files:
        print(f"Simple filename: {file}")
        # the if the file is called "log" or has a ".py" in it skip it
        if file == "log" or ".py" in file:
            continue
        # if not we can add it to our list
        # your_files.append(file)

        # if you need the full path of the file you can do this
        full_file_path = os.path.join(root, file)
        your_files.append(full_file_path)
        print(f"Full path: {file}")

print(f"Your files in a list{your_files}")
# have a look at the files list too, os.walk() creates it for you
print(files)
# or if you only need the dirs
#print(dirs)


key = Fernet.generate_key()

with open("thekey.key", "wb") as thekey:
    thekey.write(key)

for file in files:
    with open(file, "rb") as thefile:
        contents = thefile.read()
    contents_encrypted = Fernet(key).encrypt(contents)
    with open(file, "wb") as thefile:
        thefile.write(contents_encrypted)
        
print("Congratulation all files have been locked successfully")

When i am running the script, getting this error below

File “E:clear.py", line 35, in <module>
    with open(file, "rb") as thefile:
FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt'
Asked By: Ronit Roy

||

Answers:

your files are stored in "your_files" not in "files"

Change your code to:

for file in your_files: # <----
    with open(file, "rb") as thefile:
        contents = thefile.read()
    contents_encrypted = Fernet(key).encrypt(contents)
    with open(file, "wb") as thefile:
        thefile.write(contents_encrypted)
        
print("Congratulation all files have been locked successfully")

with file extensions

file_exts = [".py",".log"]
for file in your_files:
       for ext in file_exts:
            if file.endswith(ext):
                  with open(file, "rb") as thefile:
                           contents = thefile.read()
                           contents_encrypted = Fernet(key).encrypt(contents)
                  with open(file, "wb") as thefile:
                          thefile.write(contents_encrypted)
Answered By: Kiran S
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.