我想删除文件中的所有 *.ts
。但是 os.remove
不起作用。
>>> args = ['rm', '*.ts']
>>> p = subprocess.call(args)
rm: *.ts No such file or directory
最佳答案
rm
程序采用文件名列表,但 *.ts
不是文件名列表,它是匹配文件名的模式。您必须为 rm
命名实际文件。当您使用 shell 时,shell(但不是 rm
!)将为您扩展像 *.ts
这样的模式。在 Python 中,您必须明确要求它。
import glob
import subprocess
subprocess.check_call(['rm', '--'] + glob.glob('*.ts'))
# ^^^^ this makes things much safer, by the way
当然,为什么要为 subprocess
烦恼呢?
import glob
import os
for path in glob.glob('*.ts'):
os.remove(path)
关于Python:子进程调用无法识别 * 通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38758830/