【问题标题】:Impossible to delete files in a loop with python无法使用python循环删除文件
【发布时间】:2015-04-24 18:45:02
【问题描述】:

我想删除文件夹中的文件,但出现错误。

我的代码

for f in glob ('sub/*.sub'):
     subprocess.call(["php", "AES.class.php" , f])
     shutil.rmtree(f)
     #deplacement des fichier
     for d in glob ('*.ass'):
          shutil.move(d, 'sync')

它给了我以下错误:

Traceback (most recent call last):
  File "start.py", line 26, in <module>
    shutil.rmtree(f)
  File "/usr/lib64/python2.7/shutil.py", line 239, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/usr/lib64/python2.7/shutil.py", line 237, in rmtree
    names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'sub/Ep01.sub'

如何删除文件夹中扩展名为.sub的文件?

【问题讨论】:

    标签: python glob shutil eoserror


    【解决方案1】:

    您需要os.remove 而不是shutil.rmtree。具体来说,前一种方法是删除一个文件,而后一种方法是删除一个目录(连同它的所有内容)。

    for f in glob ('sub/*.sub'):
         subprocess.call(["php", "AES.class.php" , f])
         os.remove(f)
         #deplacement des fichier
         for d in glob ('*.ass'):
              shutil.move(d, 'sync')
    

    【讨论】:

      【解决方案2】:

      这里有一个例子Deleting all files in a directory with Python

      import os
      
      filelist = [ f for f in os.listdir(".") if f.endswith(".bak") ]
      for f in filelist:
          subprocess.call(["php", "AES.class.php" , f])
          os.remove(f)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-02
        • 2013-07-12
        • 2023-03-09
        • 1970-01-01
        相关资源
        最近更新 更多