[Courses] [python] Lesson 8: Extras

Akkana Peck akkana at shallowsky.com
Tue Aug 9 00:28:45 UTC 2011


Leslie writes:
> While looking up one of the expressions used in Akkana's lesson,
> os.getenv(), I discovered a host of other os methods, including
> os.chdir(), which was just what I needed.  It made me think there must
> also be os.mkdir() and os.rmdir() and I found out those work too.  (I
> also found os.uname() which gives some cool output.)

Those are great, aren't they? The os module is full of useful calls
-- you and Prana both made good use of them.

In fact, os has a couple other calls you might be interested in for your
script: os.symlink() creates a symbolic link (there's also os.link()
to make hard links), and os.remove() (you can also say os.unlink())
to remove a file.

On the other hand, if you'd used those, you wouldn't have been able
to use os.system()! :-)

There's also a sub-module of os that has some great stuff in it:
os.path, http://docs.python.org/library/os.path.html

If you've done "import os", you don't have to do any more importing
to use os.path. It includes lots of useful functions:

os.path.exists(filename) tells you if a file exists.

os.path.expanduser("~/bin") expands to "/home/yourname/bin", so
you can make a program that works for any user, not just you.

You can split pathnames into pieces:
os.path.basename("/usr/bin/python") returns "python", while
os.path.dirname("/usr/bin/python") returns '/usr/bin'.
os.path.splitext("/usr/lib/python2.6/os.py") returns a tuple,
  ('/usr/lib/python2.6/os', '.py')

You can get a file's modified/access times, and test for things
like whether something is executable, is a directory, etc.

Finally, if you write cross-platform python programs,
os.path.join("usr", "bin", "python") returns 'usr/bin/python'.
It sticks in all the slashes for you, forward slashes on Linux or
Mac and backslashes on Windows.

os is just full of good stuff. :-)

	...Akkana


More information about the Courses mailing list