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?

1
  • Why are you using subprocess for this? You should be using os.remove(). Commented Nov 15, 2014 at 8:26

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You can escape the whitespace, something like:

cmd = "rm 040513\ data.txt"
subprocess.call(cmd, shell=True)

1 Comment

You really want to avoid the shell=True instead; then you don't have to. See also Actual meaning of shell=True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.