Before reading the code, explain the important things three times:
The code only has the encrypted part. Please ensure that the encrypted file has a backup, otherwise you will bear the consequences.
The code only has the encrypted part. Please ensure that the encrypted file has a backup, otherwise you will bear the consequences.
The code only has the encrypted part, please ensure that the encrypted file has a backup, otherwise you will bear the consequences!!!
The script effect is as follows:
Before encryption.

After encryption.

Here is the code display:
import os
from cryptography.fernet import Fernet
def encrypt_file(file_path, key):
#read file content
with open(file_path, 'rb') as f:
data = f.read()
#establish Fernet object
fernet = Fernet(key)
#encrypted data
encrypted_data = fernet.encrypt(data)
#update file name
file_name, file_ext = os.path.splitext(file_path)
encrypted_file_path = file_name + file_ext + '. encrypted'
#write encrypted data
with open(encrypted_file_path, 'wb') as f:
f.write(encrypted_data)
#os.remove(file_path )if you want to delete the original file after encryption, please remove the comment on this line
#return the encrypted file path
return encrypted_file_path
#set encryption key
key = Fernet.generate_key()
#specify the path to a file
file_path = 'D:/ test .txt'#fill in the file path you want to encrypt here
#calling functions for encryption
encrypted_file_path = encrypt_file(file_path, key)