使用占位符删除文件

问题描述:

我想使用python从目录中删除多个文件。 shell命令会是什么样子使用占位符删除文件

rm *_some.tex 

当我使用这样的事情在Python中,没有得到的删除:

intermediates = ('*_some.text', '*_other.text') 
for intermediate in intermediates: 
    if os.path.isfile(intermediate): 
     os.remove(intermediate) 

如何能够做到在Python壳行为?

+0

'OS .path.isfile'不会自动扩展球体。你可能会想看看['glob'模块](https://docs.python.org/3.4/library/glob.html)。 – senshin 2015-02-05 21:21:50

+0

如果你已经把'print(intermediate)'放在'if'语句块中,你会发现'os.remove'被执行了多少次。 – 2015-02-05 23:43:22

+0

@TerryJanReedy:是的,我仍然不知道为什么。 – PVitt 2015-02-06 09:15:32

您需要使用globfnmatch才能正确放置扩展球体。加if os.path.isfile: os.remove导致一些竞赛条件。这是更好:

import glob 

globtexts = ('*_some.text', '*_other.text') 
files = [glob.glob(globtext) for globtext in globtexts] 
# try saying that line out loud five times fast.... 
for file in files: 
    try: 
     os.remove(file) 
    except Exception as e: 
     print("There was a problem removing {}: {!r}".format(file, e)) 

或者,旁边glob Python的文档中fnmatch

import fnmatch 
import os 

for file in os.listdir('.'): 
    if fnmatch.fnmatch(file, '*_some.text') or fnmatch.fnmatch(file, '*_other.text'': 
     os.remove(file) 

/home递归地做到这一点,例如,使用os.walk

for root, dirs, files in os.walk('/home'): 
    for file in files: 
     if fnmatch.fnmatch(file, '*_some.text') or fnmatch.fnmatch(file, '*_other.text'): 
      os.remove((root+'/'+file)) 
+0

感谢您的回答。我接受了亚当·斯密的回答,因为他使用了列表理解,我也需要(虽然你不知道)。 – PVitt 2015-02-06 07:55:02

+0

这是我的荣幸。我正在测试@Adam Smith的'glob',并在文档中看到'fnmatch'。我也对此感到好奇。一个小测试,我学到了一些新东西。所有人都告诉我们,对我们所有人来说,这似乎是美好的一天。 – Nodak 2015-02-06 09:02:41