Python 计划删除文件

Python schedule delete file

我正在尝试安排一个循环,让代码每隔几分钟帮助删除一个文件夹中的所有 .docx 文件。但是,我的代码实际上并没有删除文件夹中的任何 .docx 文件(我检查了路径是否正确,运行 其他代码,例如计算文件数量,还为 [= 上的终端添加了完整的磁盘访问权限23=]),循环也接收到错误。

我的代码:

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)

我得到的错误:

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'

如有任何建议,我们将不胜感激

您没有将文件名附加到您的取消链接命令。 我不熟悉 os.scandir() 所以我在下面的示例中将其更改为 os.listdir():

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))