do 'os.path' include 'os' for us?

J

Jerry Fleming

Hi,

I wrote a python script to list files in a directory but somehow did it
wrongly by importing os.path instead of os. To my astonishment, it works
just as charm:
#!/usr/bin/python
import os.path
for file in os.listdir('/root/'):
print file

I was wondering why? os.path doesn't contain listdir, why there is no
complaint like 'os: unknown name'? Does this mean, instead of importing
os, we can import os.path?

Thanks.
 
J

John Machin

Hi,

I wrote a python script to list files in a directory but somehow did it
wrongly by importing os.path instead of os. To my astonishment, it works
just as charm:
#!/usr/bin/python
import os.path
for file in os.listdir('/root/'):
        print file

I was wondering why? os.path doesn't contain listdir, why there is no
complaint like 'os: unknown name'? Does this mean, instead of importing
os, we can import os.path?

import os.path
in effect imports os, and then os.path, and injects the latter into
the former as an attribute. If it didn't, then when you tried to use
(say) os.path.join, it would raise an exception.

Why don't you do some experimentation at the interactive prompt e.g.
import os.path
type(os)
dir(os)
a = os
a.path
a = nonesuch
# The above will show you what the actual meesage is instead of
complaint like 'os: unknown name' :)

HTH,
John
 
W

Wilbert Berendsen

If i do

it seems that just import os also makes available al os.path functions.

But is that always true?

Thanks,
Wilbert
 
B

Bruno Desthuilliers

Wilbert Berendsen a écrit :
If i do

'/home/wilbert/bla'

it seems that just import os also makes available al os.path functions.

But is that always true?

Nope. Not all packages expose their sub-packages.
 
G

Gabriel Genellina

En Thu, 27 Mar 2008 14:22:11 -0300, Bruno Desthuilliers
Wilbert Berendsen a écrit :

Nope. Not all packages expose their sub-packages.

In this case, the idea is to provide an OS-dependent module with a generic
name. The os module imports one of several modules (ntpath, posixpath,
etc.) depending on the current platform, and makes it available under the
generic "path" name so users don't have to worry about that.

(Note that os is a module, not a package; os.path is accessing the "path"
attribute of the os module, not the path module in the os package)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top