使用占位符删除文件

Remove files by using placeholder

我想使用 python 从目录中删除多个文件。 shell 命令看起来像

rm *_some.tex

当我在 python 中使用类似的东西时,没有任何内容被删除:

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

如何在 python 中实现 shell 行为?

您需要使用 globfnmatch 来正确 shell 展开 glob。另外 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))

或者,Python 文档中 glob 旁边的是 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))