《python基础教程》答案(第八章)
Ch8.py
"""
solutions to beginning python
"""
import time
import os
import operator
import shutil
def print_line_lengths ( ) :
a = open ( "text.txt" , "r" )
text = a. readlines( )
for line in text:
print ( len ( line) )
def split_fully ( path) :
parent_path, name = os. path. split( path)
if name == "" :
return parent_path,
else :
return split_fully( parent_path) + ( name, )
def print_dir ( dir_path) :
for name in os. listdir( dir_path) :
print ( os. path. join( dir_path, name) )
def cmp_extension ( path0, path1) :
return operator. eq( os. path. splitext( path0) [ 1 ] , os. path. splitext( path1) [ 1 ] )
def print_dir_by_ext ( dir_path) :
for name in sorted ( os. listdir( dir_path) , cmp_extension) :
print ( os. path. join( dir_path, name) )
def print_tree ( dir_path) :
for name in os. listdir( dir_path) :
full_path = os. path. join( dir_path, name)
print ( full_path)
if os. path. isdir( full_path) :
print_tree( full_path)
def print_dir_info ( dir_path) :
for name in os. listdir( dir_path) :
full_path = os. path. join( dir_path, name)
file_size = os. path. getsize( full_path)
mod_time = time. ctime( os. path. getmtime( full_path) )
print ( "%-32s: %8d bytes, modified %s " % ( name, file_size, mod_time) )
def make_version_path ( path, version) :
if version == 0 :
return path
else :
return path + "." + str ( version)
def rotate ( path, version= 0 ) :
old_path = make_version_path( path, version)
if not os. path. exists( old_path) :
raise IOError( "'%s doesn't exist" % old_path)
new_path = make_version_path( path, version + 1 )
if os. path. exists( new_path) :
rotate( path, version + 1 )
shutil. move( old_path, new_path)
def rotate_log_file ( path) :
if not os. path. exists( path) :
new_file = open ( path, "w" )
del new_file
rotate( path)
chapter8.py
import Ch8
Ch8. print_diir( "." )
Ch8. print_line_lengths( )
print ( Ch8. split_fully( "/home/user/workspace" ) )
Ch8. print_tree( "../../" )
Ch8. print_dir_info( "../../" )
print ( Ch8. make_version_path( "./testbin" , "1.001" ) )