PermissionError: [Errno 13] Permission denied in a python program


when I run my python program I encounter an error saying:PermissionError: [Errno 13] Permission denied and I do not know why it is not working I was wondering if i could somehow elevate myself when running this program. I am using vscode and I am trying to encrypt some files.

import os
from cryptography.fernet import Fernet

# generate a random encryption key
def generate_key():
    return Fernet.generate_key()

# encrypt a file with custom byte size
def encrypt_file(key, filename, byte_size):
    with open(filename, 'rb') as f:
        data =
    cipher = Fernet(key)
    encrypted_data = cipher.encrypt(data)
    with open(filename + '.encrypted', 'wb') as f:
    return key

# save encryption key to a text file
def save_key_to_file(key):
    with open('encryption_key.txt', 'wb') as f:

# decrypt a file with a given key
def decrypt_file(key, filename):
    with open(filename, 'rb') as f:
        encrypted_data =
    cipher = Fernet(key)
    decrypted_data = cipher.decrypt(encrypted_data)
    with open('decrypted_' + filename, 'wb') as f:

# me
# ain function
def main():
    choice = input("Enter 'E' to encrypt or 'D' to decrypt: ").upper()
    if choice == 'E':
        byte_size = int(input("Enter the byte size for encryption: "))
        filename = input("Enter the name of the file to encrypt: ")
        key = generate_key()
        encrypt_file(key, filename, byte_size)
        print("Encryption completed.")
        print("Encryption key has been saved to 'encryption_key.txt'.")
    elif choice == 'D':
        key = input("Enter the decryption key: ")
        filename = input("Enter the name of the encrypted file to decrypt: ")
        decrypt_file(key, filename)
        print("Decryption completed.")
        print("Invalid choice. Please enter 'E' or 'D'.")

if __name__ == "__main__":

I have not tried anything because I do not even know where to start

Asked By: Aiden



I have tried your code using vscode, seems like there is no problem to it.
However i manage to create the same error you are facing, If you are trying to Encrypt a folder, it will show the Error you mentioned "PermissionError: [Errno 13] Permission denied: ‘the_folder_name’" Since the code is for encrypting file and not folder

Make sure the targeted file is specified.

Answered By: Jovian
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.