我想使用 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 行为?
最佳答案
您需要使用 glob
或 fnmatch
来正确地对 glob 进行 shell 扩展。另外 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 - 使用占位符删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28354156/