D
D
dstoric5432021-06-29 05:38:04
Python
dstoric543, 2021-06-29 05:38:04

How to fix FileNotFoundError: [Errno 2] No such file or directory:?

The e:/1 directory has a file and subfolders that also contain files. You need to encrypt all files in the directory and subdirectories. Of course, in the directory, I was able to perform this action, I was able to read and write to the "catalogi" variable and was able to encrypt the directory I specified, but when I try to use the catalogi variable (in which the directories are located) called by os.scandir, I get an error:

FileNotFoundError: [Errno 2] No such file or directory: 'e:/1\\Новая папка — копия (6)Новый текстовый документ.txt'


On line 23 read_file = open(catalogi+entry.name, 'rb').read()

Help me decide.

import os, sys
from cryptography.fernet import Fernet
for catalogi, subdirs, files in os.walk('e:/1'):
    for name in files:
        print(os.path.join(catalogi))
key = Fernet.generate_key()
if not os.path.exists('pass.txt'):
    with open('pass.txt', 'wb') as f:
        f.write(key)
else:
    key = open('pass.txt', 'rb').read()
print(key)
cipher = Fernet(key)

encrypt_yes = True

if encrypt_yes:
    with os.scandir(path=catalogi) as it:
        for entry in it:
            if not entry.is_file():
                print("dir:\t" + entry.name)
            else:
                read_file = open(catalogi+entry.name, 'rb').read()
                encrypted_file_content = cipher.encrypt(read_file)
                with open(catalogi+entry.name, 'wb') as f:
                    f.write(encrypted_file_content)
                print("file encrypted:\t" + entry.name)
else:
    with os.scandir(path=catalogi) as it:
        for entry in it:
            if not entry.is_file():
                print("dir:\t" + entry.name)
            else:
                encrypted_file_content = open(catalogi+entry.name, 'rb').read()
                file_content = cipher.decrypt(encrypted_file_content)
                with open(catalogi+entry.name, 'wb') as f:
                    f.write(file_content)
                print("file decrypted:\t" + entry.name)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-06-29
@phaggi

Use pathlib.Path
Path objects are connected with "/", for example:

from pathlib import Path
my_root = Path('c:')
my_dir = Path('new_dir')
my_file = Path('new_file.txt')
full_file_path = my_root / my_dir / my_file
print(full_file_path)
print(type(full_file_path))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question