'Moving file to Recycle Bin
I'm trying to move file to recycle bin using shutil library. Following is relevant code lines, but I get kinda strange error. Both files are local, and I can access both locations on my PC. Why this error occurs? Because I run Main.py it from F:?
import shutil
# Path to folder where files should be trashed
dump_folder = r"C:\$Recycle.Bin\\"
file_name = "C:\\Storage\\\\statuti.docx"
# Move it to storage directory
shutil.move(file_name, dump_folder)
Error message
F:\Python\Project\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 54648 --file F:\Python\Main.py Connected to pydev debugger (build 203.5981.165) Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\shutil.py", line 788, in move os.rename(src, real_dst) PermissionError: [WinError 5] Access is denied: 'C:\Storage\\statuti.docx' -> 'C:\Recycle.Bin\\'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\shutil.py", line 261, in copyfile with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: OSError: [Errno 22] Invalid argument: 'C:\Recycle.Bin\\'
Solution 1:[1]
To send something to the recycle bin it is much easier to use send2trash
. It is cross platform and very easy to use.
You can install it with :
pip install Send2Trash
Then you can use it :
from send2trash import send2trash
send2trash(filename)
Solution 2:[2]
I would suggest you install the Send2Trash module, which works across platforms. You can get it from PyPi: https://pypi.org/project/Send2Trash/
Solution 3:[3]
I'm using Windows 10 and send2trash
is only accepting path with backslash \
. It throws OSError: [WinError xxxxxxxxxx] The parameter is incorrect
when you tried to pass a directory with forward slash /
.
This code should replace the /
with \
, and fix the error:
path_to_delete = path_to_delete.replace("/", "\\")
send2trash(path_to_delete)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Mario Camilleri |
Solution 3 | Eliazar |