《python基础教程》答案(第八章)

《python基础教程》答案(第八章)

Ch8.py

# created by swy
"""
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"))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值