使用占位符删除文件
问题描述:
我想使用python从目录中删除多个文件。 shell命令会是什么样子使用占位符删除文件
rm *_some.tex
当我使用这样的事情在Python中,没有得到的删除:
intermediates = ('*_some.text', '*_other.text')
for intermediate in intermediates:
if os.path.isfile(intermediate):
os.remove(intermediate)
如何能够做到在Python壳行为?
答
您需要使用glob
或fnmatch
才能正确放置扩展球体。加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))
'OS .path.isfile'不会自动扩展球体。你可能会想看看['glob'模块](https://docs.python.org/3.4/library/glob.html)。 – senshin 2015-02-05 21:21:50
如果你已经把'print(intermediate)'放在'if'语句块中,你会发现'os.remove'被执行了多少次。 – 2015-02-05 23:43:22
@TerryJanReedy:是的,我仍然不知道为什么。 – PVitt 2015-02-06 09:15:32