如何使用os.remove在python中修复PermissionError:[WinError 32]?

时间:2019-08-16 12:27:47

标签: python encryption cryptography rsa

我的代码中出现一个 PermissionError:[WinError 32] 问题。必须先将文件解密,然后再删除(加密)。但是该文件仅被解密,文件夹中保留了两个文件:加密和解密。

可能是什么问题?

我已经尝试过延迟解密和删除之间的时间。

def decrypt(file):

    file_in = open(file, "rb")
    file_out = open(str(file[:-4]), "wb")
    rivate_key = RSA.import_key(open("private.pem").read())

    enc_session_key, nonce, tag, ciphertext = \
       [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

    cipher_rsa = PKCS1_OAEP.new(private_key)
    session_key = cipher_rsa.decrypt(enc_session_key)

    cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
    data = cipher_aes.decrypt_and_verify(ciphertext, tag)
    file_out.write(data)
    print(file + " DECRYPT!")
    time.sleep(5)
    os.remove(file)

出现以下错误:

>Traceback (most recent call last):
File "C:/Users/user/Desktop/codes on python/decrypt.py", line 31, in <module>
    walk("C:\\Users\\user\\Desktop\\codes on python\\papka")  
File "C:/Users/user/Desktop/codes on python/decrypt.py", line 28, in walk
    if os.path.isfile(path): decrypt(path)  
File "C:/Users/user/Desktop/codes on python/decrypt.py", line 23, in decrypt
    os.remove(file)
PermissionError: [WinError 32] Процесс не может получить доступ к файлу, так как этот файл занят другим процессом: 'C:\\Users\\user\\Desktop\\codes on python\\papka\\data.data.bin'

1 个答案:

答案 0 :(得分:0)

您必须先关闭文件,然后才能删除它们

您必须运行: file_in.close(),然后再运行 os.remove(file)

这将允许操作系统访问文件,就像python持有文件之前一样。

相关问题