Home > Net >  How can I convert a PureWindowsPath to a Iterable?
How can I convert a PureWindowsPath to a Iterable?

Time:04-23

I'm working on an academy project to encrypt some files I have managed to encrypt all files from one folder but when there is a folder into that folder i get errors so i decide to first list all files and sub-directories of the folder:

ROOT = r"C:\Users\Practiques\Desktop\archivos"

    for path, subdirs, files in os.walk(ROOT):
        for name in files:
            pure_path = PurePath(path, name)
            print (pure_path)

With this code I get the paths in that form: C:\Users\XXX\Desktop\archivos\external-content.duckduckgo.com.jpg C:\Users\XXX\Desktop\archivos\hola.txt

and then when i try to pass to the function 'encrypt', i get this error:

TypeError: 'PureWindowsPath' object is not iterable

The format I need to pass to the function is this: ['C:\Users\XXX\Desktop\archivos\external-content.duckduckgo.com.jpg', 'C:\Users\XXX\Desktop\archivos\hola.txt', etc.]

I think one possible solution is to make a list when i obtain all recursive path and their files, but i don't know how to do that.

The function encrypt:

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)

How i call it:

for path, subdirs, files in os.walk(ROOT):
    for name in files:
        pure_path = PurePath(path, name)
        print (pure_path)
        encrypt(pure_path, key)

CodePudding user response:

You need to use recursion to encrypt the sub-folders' contents:

import os

def recursive_search(path: str) -> "list[str]":
    """get all files from an absolute path

    :param path: absolute path of the directory to search
    :type path: str
    :return: a list of all files
    :rtype: list[str]
    """
    found_files = []
    if not os.path.isdir(path):
        raise RuntimeError(f"'{path}' is not a directory")
    for item in os.listdir(path):
        full_path = os.path.join(path, item)
        if os.path.isfile(full_path):
            found_files.append(full_path)
        elif os.path.isdir(full_path):
            found_files.extend(recursive_search(full_path))
    return found_files

directory = "YOUR ROOT/TOP-LEVEL DIRECTORY HERE"
print(recursive_search(directory))

Then, you would do:

f = Fernet(key)
for item in recursive_search(directory):
    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)
  • Related