How to work with directories and files with spaces

Larry Bates larry.bates at websafe.com
Thu Apr 6 12:41:37 EDT 2006


s99999999s2003 at yahoo.com wrote:
> hi
> 
> I am working in unix and i have some directories names with spaces
> eg ABC DEF A
> how can i work effectively with spaces in directory/file names in
> python?
> 
> sometimes when i do os.path.join(dir_with_spaces,"-somestring" ) , it
> gives me "-somestring"  as the name only...without ABC DEF A
> it should give me ABC DEF A-somestring as the directory name
> 
> thanks
> 

The spaces aren't the problem AND you are misreading what
os.path.join does:

join( path1[, path2[, ...]])

Joins one or more path components intelligently. If any component
is an absolute path, all previous components are thrown away, and
joining continues. The return value is the concatenation of path1,
and optionally path2, etc., with exactly one directory separator
(os.sep) inserted between components, unless path2 is empty. Note
that on windows, since there is a current directory for each drive,
os.path.join("c:", "foo") represents a path relative to the current
directory on drive C: (c:foo), not c:\\foo.


>>> dir_with_spaces="ABC DEF A"
>>> import os
>>> os.path.join(dir_with_spaces, '-somestring')
'ABC DEF A\\-somestring'
>>>

To do what you wanted (based on your example) I would do:

import os
fullpath="%s%s" % (dir_with_spaces, '-somestring')

-Larry Bates



More information about the Python-list mailing list