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
  • 192
  • 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
  • 205,541
  • 37
  • 345
  • 415
  • What does "this" make much safer and why? – miterhen Jun 19 '23 at 16:05
  • 1
    The `--` parameter separates flags like `-f` from filenames. If you have a file named `-f`, then you can remove it using `rm -- -f`, but you cannot remove it using `rm -f`, because it is interpreted as a flag. – Dietrich Epp Jun 20 '23 at 13:44
  • Ok, fair enough. Though I'd argue if someone accidentally deletes a file they called `-f` they probably had it coming. – miterhen Jun 21 '23 at 20:45
  • The problem sometimes comes up because people allow users to choose filenames, and then somebody else (besides the user who created the file) goes in to do some administrative work. – Dietrich Epp Jun 22 '23 at 04:09