how to proccess the blank in the path on linux

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Wed May 21 11:05:03 EDT 2008


On 2008-05-21, zhf <mypromise at sina.com> wrote:
> I want ro walk a directory and its sub directory on linux,
> to find some shell script file, and run them, but I found some path belong
> blank charactor, such as '8000 dir', if I write as follow, I got error
> "no such file"
> path = '8000 dir'
> for root, dirs, files in os.walk(path):
> cmd = ' '
> cmd = 'cd ' + root
> os.system(cmd)
>
> How can I repair it?

Escape the space to prevent the shell from interpreting it as a word seperator.
This of course also holds for all other shell meta characters,
such as * [ ] \ > < & and a few others I probably have forgotten.


I am not sure why you execute 'cd' commands in a sub-shell, as it is not very
useful. (that is, you start a new sub-process, in that sub-process you run the
'cd' command (causing the cwd of the sub-process to change directory), and then
the sub-process ends)

You most likely want to change the cwd of the Python process. If so, have a
look at os.chdir(). That function has the added advantage that there is no
shell in between that interprets all those meta characters (that is,
"os.chdir('8000 dir')" will work without further effort).

Sincerely,
Albert



More information about the Python-list mailing list