0

Given:

/some/path/to/a/certain unspecified/folder/

I need a list:

var = some, path, to, a, "certain unspecified", folder

I suspect os.walk(dir) might have something to do with it, but I can't seem to make this work...

Sorry I'm fairly new to Python.

1
  • I think you mean var = ["some", "path", "to", "a", "certain unspecified", "folder"] Commented Jan 11, 2014 at 5:31

3 Answers 3

1

split is the key:

var = '/some/path/to/a/certain unspecified/folder/'.split('/')
Sign up to request clarification or add additional context in comments.

2 Comments

oooh. Split looks like it may do... --- except what happens when the user is on a Windoze machine, and the dir is '\'
and os.listdir gives the contents of that path... not quite the same
1

Unless you're on windows, mangling linux paths, use os.path.split. Or set os.sep to your liking. This is not going to work with mixed windows and linux paths, unless you change the path separator appropriately, just before splitting.

Edit2: Setting os.path.sep WON'T make os.path.split or os.path.join behave any different. Sorry.

Edit: Um, right, os.path.split gets the final component. There is, however, os.altsep, so path.replace(os.altsep,os.sep).split(os.sep) might be the way.

os.sep is by default set to your OS' preferred one. os.pathsep is (on windows) what separates directories in PATH variable.

To make it reliable normalize the path (as suggested by @mhlester):

>>> os.path.normpath(r"C:/PythoN27\python.exe")
'C:\\PythoN27\\python.exe'
>>> os.path.normcase(r"C:/PythoN27\python.exe")
'c:\\python27\\python.exe'

3 Comments

the environment will be stable - just can't control what enviro it'll be run in...
This is possibly the better answer than mine. It depends on how the path is built. Most of the time I spend on Windows still uses '/', but likely it should be normalized first regardless.
os.path.split('/a/b/c/d') yields ('/a/b/c', 'd'). That is not what OP want.
0

answer to except what happens when the user is on a Windoze machine, and the dir is '\'

Use os.sep to get the path separator of current os:

In [254]: os.getcwd()
Out[254]: 'D:\\Documents\\Desktop'

In [255]: os.getcwd().split(os.sep)
Out[255]: ['D:', 'Documents', 'Desktop']

1 Comment

Perefect. os.sep seems to be key

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.