【发布时间】:2022-06-17 10:13:06
【问题描述】:
当我运行我的代码时,我运行我的加密文件的代码我得到这个错误
<_io.TextIOWrapper name='C:/Users/depen/OneDrive/Documents/PNG_transparency_demonstration_1 >(2).png' mode='r' encoding='cp1252'>
read
encrypting
encrypted
encrypted file saved
Traceback (most recent call last):
File "c:\Users\depen\OneDrive\Documents\python\timer\encrypt.py", line 93, in <module>
encrypt(fpath)
File "c:\Users\depen\OneDrive\Documents\python\timer\encrypt.py", line 67, in encrypt
os.rename(file_fpath, file_fpath + ".encrypted")
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/depen/OneDrive/Documents/PNG_transparency_demonstration_1 (2).png' -> 'C:/Users/depen/OneDrive/Documents/PNG_transparency_demonstration_1 (2).png.encrypted'
这是我的代码
def encrypt(file_path):
file_fpath = file_path.name
#use Path.read_bytes to read from file_fpath
data = Path(file_fpath).read_bytes()
print ("read")
print ("encrypting")
#encrypt the file with the key
encrypted_file = fernet.encrypt(data)
print ("encrypted")
Path(file_fpath).write_bytes(encrypted_file)
print ("encrypted file saved")
#rename the file to .encrypted
os.rename(file_fpath, file_fpath + ".encrypted")
这是我何时以及如何称呼它
encrypt(fpath)
with open("file_names.txt", "a") as file_names:
file_names.write(fpath.name + "\n")
file_names.close()
print (fpath.name + "encrypted")
【问题讨论】:
-
我可以使用 ``` 和 open() ``` 但这对我来说很慢,因为读取大文件需要很长时间
-
旁注:您正确使用了
with语句,file_names.close()是不必要的,应该删除(with负责清理)。
标签: python file encryption