2

I'm using subprocess to remove files in python, some of the file name has white space in it. How could I handle this? For example, I have a file named '040513 data.txt'

subprocess.call(['rm', '040513 data.txt'], shell=True)

But I got error like IOError: [Errno 2] No such file or directory How could I fix this?

  • Why are you using `subprocess` for this? You should be using [os.remove()](https://docs.python.org/2/library/os.html#os.remove). – PM 2Ring Nov 15 '14 at 08:26

2 Answers2

1

You can also pass a list of args to call. This takes cares of parameters and also you avoid the shell=True security issue:

subprocess.call(['rm', '040513 data.txt'])

If for any reason you wanted to use shell=True then you could also use quotes to escape blanks as you would do in a shell:

subprocess.call('rm "040513 data.txt"', shell=True)
dreyescat
  • 13,558
  • 5
  • 50
  • 38
0

You can escape the whitespace, something like:

cmd = "rm 040513\ data.txt"
subprocess.call(cmd, shell=True)
Ankush Shah
  • 938
  • 8
  • 13
  • You really want to avoid the `shell=True` instead; then you don't have to. See also [Actual meaning of `shell=True`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Feb 17 '21 at 12:40