【问题标题】:Deleting all files in a directory with Python使用Python删除目录中的所有文件
【发布时间】:2011-01-01 00:13:30
【问题描述】:

我想删除目录中所有扩展名为.bak 的文件。我如何在 Python 中做到这一点?

【问题讨论】:

  • @slh2080:发布“已解决”不是您在此站点上所做的。您要做的是选择您实际使用的答案,然后单击复选标记以表明它解决了您的问题。
  • 对不起。感谢您指出我的错误。这不是功课,只是在业余时间学习python。我点击了我使用的答案,但那是在我看到 ghostdog74 响应之前。
  • 注意:删除整个目录树shutil.rmtree(path) could used

标签: python file-io


【解决方案1】:

通过os.listdiros.remove

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

只使用一个循环:

for f in os.listdir(mydir):
    if not f.endswith(".bak"):
        continue
    os.remove(os.path.join(mydir, f))

或通过glob.glob

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)

确保在正确的目录中,最终使用os.chdir

【讨论】:

  • 您的第一个示例是使用冗余 for 循环。您可以通过 - [ os.remove(f) for f in os.listdir(".") if f.endswith(".bak") ] - 因为列表推导是要使用的。或者您可以将理解中的“if”移动到 for 循环中 - for f in os.listdir("."): if f.endswith(".bak"): os.remove(f)
  • @slh2080 既然你说问题已经解决了,为什么不把答案标记为正确答案呢?
  • 当心 os.listdir(".") !!!我用了这段代码,忘了改路径,我所有的代码都不见了!!!尝试了两种不同的实用程序来恢复,但没有成功!
  • @LeiGuo 解决了这个问题。
  • @dragonjujo 我认为调用副作用非常不是列表推导的使用方式。
【解决方案2】:

我意识到这是旧的;然而,这里将是如何只使用 os 模块来做到这一点......

def purgedir(parent):
    for root, dirs, files in os.walk(parent):                                      
        for item in files:
            # Delete subordinate files                                                 
            filespec = os.path.join(root, item)
            if filespec.endswith('.bak'):
                os.unlink(filespec)
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))

【讨论】:

    【解决方案3】:

    在 Linux 和 macOS 上,您可以对 shell 运行简单的命令:

    subprocess.run('rm /tmp/*.bak', shell=True)
    

    【讨论】:

    • 在我看来不是一个好的选择。它不是可移植的,而且由于额外的子进程,它可能更昂贵。最好使用 Python API。
    • 此解决方案依赖于平台,而 Python 与平台无关。
    【解决方案4】:

    在 Python 3.5 中,如果您需要检查文件属性或类型,os.scandir 会更好 - 有关函数返回的对象的属性,请参阅 os.DirEntry

    import os 
    
    for file in os.scandir(path):
        if file.name.endswith(".bak"):
            os.unlink(file.path)
    

    这也不需要更改目录,因为每个DirEntry 已经包含文件的完整路径。

    【讨论】:

    • 你少了一个冒号,for循环内的第一行应该是if file.name.endswith(".bak"):
    • 谢谢!这将教我编写代码而不实际运行它们
    • 你好,如何创建路径对象?
    【解决方案5】:

    你可以创建一个函数。为遍历子目录添加你喜欢的 maxdepth。

    def findNremove(path,pattern,maxdepth=1):
        cpath=path.count(os.sep)
        for r,d,f in os.walk(path):
            if r.count(os.sep) - cpath <maxdepth:
                for files in f:
                    if files.endswith(pattern):
                        try:
                            print "Removing %s" % (os.path.join(r,files))
                            #os.remove(os.path.join(r,files))
                        except Exception,e:
                            print e
                        else:
                            print "%s removed" % (os.path.join(r,files))
    
    path=os.path.join("/home","dir1","dir2")
    findNremove(path,".bak")
    

    【讨论】:

      【解决方案6】:

      使用os.chdir 更改目录。 使用glob.glob 生成以“.bak”结尾的文件名列表。列表的元素只是字符串。

      然后您可以使用os.unlink 删除文件。 (PS.os.unlinkos.remove是同一个函数的同义词。)

      #!/usr/bin/env python
      import glob
      import os
      directory='/path/to/dir'
      os.chdir(directory)
      files=glob.glob('*.bak')
      for filename in files:
          os.unlink(filename)
      

      【讨论】:

        【解决方案7】:

        首先是glob 他们,然后是unlink

        【讨论】:

          猜你喜欢
          • 2014-06-03
          • 2010-11-05
          • 2013-07-31
          • 2020-12-20
          • 2014-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多