>>> open('spam.txt', 'w').write('Hello stat world\n') # +1 for \r added
17
>>> import os
>>> info = os.stat(r'C:\temp\spam.txt')
>>> info
nt.stat_result(st_mode=33206, st_ino=0, st_dev=0, st_nlink=0, st_uid=0, st_gid=0,
st_size=18, st_atime=1267645806, st_mtime=1267646072, st_ctime=1267645806)
>>> info.st_mode, info.st_size # via named-tuple item attr names
(33206, 18)
>>> import stat
>>> info[stat.ST_MODE], info[stat.ST_SIZE] # via stat module presets
(33206, 18)
>>> stat.S_ISDIR(info.st_mode), stat.S_ISREG(info.st_mode)
(False, True)
The os.stat call returns a tuple of values (really, in 3.X a special kind of tuple with
named items) giving low-level information about the named file, and the stat module
exports constants and functions for querying this information in a portable way. For
instance, indexing an os.stat result on offset stat.ST_SIZE returns the file’s size, and
calling stat.S_ISDIR with the mode item from an os.stat result checks whether the file
is a directory. As shown earlier, though, both of these operations are available in the
os.path module, too, so it’s rarely necessary to use os.stat except for low-level file
queries:
>>> path = r'C:\temp\spam.txt'
>>> os.path.isdir(path), os.path.isfile(path), os.path.getsize(path)
(False, True, 18)
File Scanners
Before we leave our file tools survey, it’s time for something that performs a more
tangible task and illustrates some of what we’ve learned so far. Unlike some shell-tool
languages, Python doesn’t have an implicit file-scanning loop procedure, but it’s simple
to write a general one that we can reuse for all time. The module in Example 4-1 defines
a general file-scanning routine, which simply applies a passed-in Python function to
each line in an external file.
Example 4-1. PP4E\System\Filetools\scanfile.py
def scanner(name, function):
file = open(name, 'r') # create a file object
while True:
line = file.readline() # call file methods
if not line: break # until end-of-file
function(line) # call a function object
file.close()
The scanner function doesn’t care what line-processing function is passed in, and that
accounts for most of its generality—it is happy to apply any single-argument function
160 | Chapter 4: File and Directory Tools