12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

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.

14.4. Filenames and paths 137>>> '%d %d %d' % (1, 2)TypeError: not enough arguments for format string>>> '%d' % 'dollars'TypeError: illegal argument type for built-in operationInthefirstexample, therearen’t enough elements; inthesecond, the element isthe wrong type.The format operator is powerful, but it can be difficult to use. You can read more about it at docs.python.org/lib/typesseq-strings.html.14.4 Filenamesand pathsFiles are organized into directories (also called “folders”). Every running program has a “currentdirectory,”whichisthedefaultdirectoryformostoperations. Forexample,whenyouopenafileforreading, <strong>Python</strong> looks foritinthe current directory.Theosmoduleprovidesfunctionsforworkingwithfilesanddirectories(“os”standsfor“operatingsystem”). os.getcwdreturnsthe name of the current directory:>>> import os>>> cwd = os.getcwd()>>> print cwd/home/dinsdalecwd stands for “current working directory.” The result in this example is /home/dinsdale, whichisthehome directory of auser nameddinsdale.A string like cwd that identifies a file is called a path. A relative path starts from the currentdirectory; anabsolute path startsfromthe topmost directory inthefile system.The paths we have seen so far are simple filenames, so they are relative to the current directory. Tofind the absolute path toafile, you can useos.path.abspath:>>> os.path.abspath('memo.txt')'/home/dinsdale/memo.txt'os.path.existschecks whether a fileor directory exists:>>> os.path.exists('memo.txt')TrueIfitexists,os.path.isdirchecks whether it’sadirectory:>>> os.path.isdir('memo.txt')False>>> os.path.isdir('music')TrueSimilarly,os.path.isfilechecks whether it’safile.os.listdirreturns alistofthe files (and other directories) inthegiven directory:>>> os.listdir(cwd)['music', 'photos', 'memo.txt']

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

Saved successfully!

Ooh no, something went wrong!