Dive into python 3 chapter 3
os
module hasos.getcwd()
andos.chdir()
1 functions, note that When calling theos.chdir()
function, use a Linux-style pathname (forward slashes, no drive letter) even on Windows.
eg:
os.chdir(‘/Users/pilgrim/diveintopython3/examples’)os.path.join()
will take any number of arguments andos.path.expanduser()
function will expand a pathname that uses ~ to represent the current user’s home directory.os.path.split()
return a tuple of two variables (the directory name and the filename), andsplitext()
will return name and extension.- the glob function can be used to get the contents of a directory using wildcards. consult glob reference here or here.
- get metadata of a file using
os.stat()
2:>>> metadata = os.stat('feed.xml') >>> metadata.st_size 3070
- list and dictionary comprehnsions are easy ways to construct new lists and dictionaries based on given ones.
A comprehensive usage example
>>> import os, glob
>>> glob.glob('*.xml')
['feed-broken.xml', 'feed-ns0.xml', 'feed.xml']
>>> [os.path.realpath(f) for f in glob.glob('*.xml') if os.stat(f).st_size > 1000]
['c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-broken.xml',
'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-ns0.xml',
'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed.xml']