2

I want to remove all the *.ts in file. But os.remove didn't work.

>>> args = ['rm', '*.ts']
>>> p = subprocess.call(args)
rm: *.ts No such file or directory
panda0
  • 172
  • 1
  • 18
  • Possible duplicate of [Calling rm from subprocess using wildcards does not remove the files](http://stackoverflow.com/questions/11025784/calling-rm-from-subprocess-using-wildcards-does-not-remove-the-files) – tripleee Aug 04 '16 at 06:04

1 Answers1

12

The rm program takes a list of filenames, but *.ts isn't a list of filenames, it's a pattern for matching filenames. You have to name the actual files for rm. When you use a shell, the shell (but not rm!) will expand patterns like *.ts for you. In Python, you have to explicitly ask for it.

import glob
import subprocess
subprocess.check_call(['rm', '--'] + glob.glob('*.ts'))
#                            ^^^^ this makes things much safer, by the way

Of course, why bother with subprocess?

import glob
import os
for path in glob.glob('*.ts'):
    os.remove(path)
Dietrich Epp
  • 194,726
  • 35
  • 326
  • 406