I'm trying to schedule a loop that every mins the code will help delete all the .docx
files in a folder. However my code is not actually deleting any .docx
files on the folder (I checked that the path is right and run other code like count the number of files, also add full disk access for Terminal on Mac), and the loop also receiving error.
my code:
import os, os.path
import time
import schedule
csv_count = len(os.listdir("/Users/xxx/Desktop/FYP 1st Draft"))
def delectfiles():
for file in os.scandir("/Users/xxx/Desktop/FYP 1st Draft"):
if file.name.endswith(".docx"):
os.unlink("/Users/xxx/Desktop/FYP 1st Draft")
schedule.every().minute.do(delectfiles)
while True:
schedule.run_pending()
time.sleep(1)
the error I got:
Traceback (most recent call last):
File "/Users/xxx/PycharmProjects/Jedox_batch/Jedox.py", line 16, in <module>
schedule.run_pending()
File "/Users/xxx/PycharmProjects/Jedox_batch/venv/lib/python3.8/site-packages/schedule/__init__.py", line 780, in run_pending
default_scheduler.run_pending()
File "/Users/xxx/PycharmProjects/Jedox_batch/venv/lib/python3.8/site-packages/schedule/__init__.py", line 100, in run_pending
self._run_job(job)
File "/Users/xxx/PycharmProjects/Jedox_batch/venv/lib/python3.8/site-packages/schedule/__init__.py", line 172, in _run_job
ret = job.run()
File "/Users/xxx/PycharmProjects/Jedox_batch/venv/lib/python3.8/site-packages/schedule/__init__.py", line 661, in run
ret = self.job_func()
File "/Users/xxx/PycharmProjects/Jedox_batch/Jedox.py", line 11, in delectfiles
os.unlink("/Users/xxx/Desktop/FYP 1st Draft")
PermissionError: [Errno 1] Operation not permitted: '/Users/xxx/Desktop/FYP 1st Draft'
Any suggestions would be appreciated
CodePudding user response:
You are not appending the filename to your unlink command. I'm not familiar with os.scandir() so I changed it to os.listdir() in my example below:
def delectfiles():
for file in os.listdir("/Users/xxx/Desktop/FYP 1st Draft"):
if file.name.endswith(".docx"):
os.unlink(os.path.join("/Users/xxx/Desktop/FYP 1st Draft/", file))