三行代码  ›  专栏  ›  技术社区  ›  Bellasere

Python计划删除文件

  •  1
  • Bellasere  · 技术社区  · 1 月前

    .docx 文件夹中的文件。然而,我的代码实际上并没有删除任何内容 .docx 文件夹上的文件(我检查了路径是否正确,并运行了其他代码,如计算文件数,还为Mac上的终端添加了完整的磁盘访问),循环也收到了错误。

    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'
    

    1 回复  |  直到 1 月前
        1
  •  2
  •   Mikael Kjær    1 月前

    您没有将文件名附加到unlink命令。 我不熟悉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))