15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[]<br />

*** creating test file...<br />

*** updated directory listing:<br />

['test']<br />

*** renaming 'test' to 'filetest.txt'<br />

*** updated directory listing:<br />

['filetest.txt']<br />

*** full file pathname:<br />

c:\windows\temp\example\filetest.txt<br />

*** (pathname, basename) ==<br />

('c:\\windows\\temp\\example', 'filetest.txt')<br />

*** (filename, extension) ==<br />

('filetest', '.txt')<br />

*** displaying file contents:<br />

foo<br />

bar<br />

*** deleting test file<br />

*** updated directory listing:<br />

[]<br />

*** deleting test directory<br />

*** DONE<br />

Rather than providing a line-by-line explanation here, we will leave it to the reader as an exercise.<br />

However, we will walk through a similar interactive example (including errors) to give you a feel for<br />

what it is like to execute this script one step at a time. We will break into the code every now and then<br />

to describe the code we just encountered.<br />

>>> import os<br />

>>> os.path.isdir('/tmp')<br />

True<br />

>>> os.chdir('/tmp')<br />

>>> cwd = os.getcwd()<br />

>>> cwd<br />

'/tmp'<br />

This first block of code consists of importing the os module (which also grabs the os.path module). We<br />

verify that '/tmp' is a valid directory and change to that temporary directory to do our work. When we<br />

arrive, we call the getcwd() method to tell us where we are.<br />

>>> os.mkdir('example')<br />

>>> os.chdir('example')<br />

>>> cwd = os.getcwd()<br />

>>> cwd<br />

'/tmp/example'<br />

>>><br />

>>> os.listdir() # oops, forgot name<br />

Traceback (innermost last):<br />

File "", line 1, in ?<br />

TypeError: function requires at least one argument<br />

>>><br />

>>> os.listdir(cwd) # that's better :)<br />

[]<br />

Next, we create a subdirectory in our temporary directory, after which we will use the listdir() method

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!