how to handle white space in filename when using subprocess in python

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?

Upvotes: 2

Views: 5332

Answers (2)

dreyescat
dreyescat

Reputation: 13818

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)

Upvotes: 1

Ankush Shah
Ankush Shah

Reputation: 958

You can escape the whitespace, something like:

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

Upvotes: 0

Related Questions