If you convert a PathInfo object to a string, it starts with
the permissions. However, in the bigfiles.py script, we're
assuming that the user is not going to interested in
permissions, but mainly in the file's size and pathname,
and perhaps also its last modification time.
So, to change this format, we can define a __str__() method to override the base
class's .__str__() method.
This version of the method presents only the modification
time, file size, and path name.
There is one refinement to make the display more
readable. Because this version of .__str__() does not include the type code
(d for directory, - for regular files), it is hard to tell
which pathnames relate to directories. So we append a
"/" to the pathname if it is a
directory. This is the convention used by the output of
the “ls -F”
command to identify directories.
# - - - B i g I n f o . _ _ s t r _ _ - - -
def __str__ ( self ):
"""Format a BigInfo for printing."""
So that the reader of the report can tell which lines are
for directories, we set suffix to a slash
if this path is a directory, or to an empty string
otherwise.
#-- 1 --
# [ if self represents a directory ->
# suffix := "/"
# else ->
# suffix := "" ]
if self.isDir(): suffix = "/"
else: suffix = ""
Next we find the path relative to self.__basePath. This code assumes that self.__basePath is the absolute path name of a
directory above our path. To get the relative path,
we can then just use os.path.abspath() to
get our path's absolute path, then trim off the first
len(self.__basePath) characters, plus
one for the slash that separates those two parts.
#-- 2 --
# [ self.__basePath is the absolute path of a directory
# above self.path ->
# relPath := path to self.path relative to
# self.__basePath ]
absPath = os.path.abspath ( self.path )
relPath = absPath [ len(self.__basePath) + 1 : ]
There is one special case: the first line of the report
is for the base path itself, whose absolute path is
identical to self.__basePath, and
relPath is now an empty string. In this
case, we substitute "." for the path name,
and set suffix to the empty string so
that the line will not read "./".
#-- 3 --
if relPath == "":
relPath = "."
suffix = ""
Finally we are ready to format and return the report line.
#-- 4 --
return ( "%s %10s %s%s" %
(self.modTime(), self.size, relPath, suffix) )