1. 程式人生 > >Python核心程式設計 第九章練習

Python核心程式設計 第九章練習

筆者剛剛開始Python的系統學習,所以在程式碼上還無法達到pythonic的水準,很多寫法也都是按照C++的習慣來寫的,希望能有前輩進行交流指導。

歡迎拍磚

9_1

#!/usr/bin/python2
# coding: utf-8

if __name__ == '__main__':
    with open('example.txt') as f:
        for each_line in f:
            if '#' in each_line:
                pos = each_line.find('#')
                if
pos > 0: print each_line[: pos] else: continue else: print each_line

9_2

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if
os.path.isfile(curdirF): return curdirF return if __name__ == '__main__': F = raw_input('Please input the file name: ') file_path = FilePathCheck(F) if file_path: with open(file_path) as f: N = int(raw_input('Please input the line number: ')) for
i in range(N): print f.readline(), else: print 'the file name is not valid!'

9_3

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            lst_line = f.readlines()
            print 'the number of rows are %s' %len(lst_line)
    else:
        print 'the file name is not valid!'

9_4


#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            while True:
                try:
                    raw_input('Press any key to continue...')
                    for i in range(25):
                        line = f.readline()
                        if line == '':
                            raise EOFError
                        print line,
                except(EOFError, KeyboardInterrupt):
                    break

    else:
        print 'the file name is not valid!'

9_5

#!/usr/bin/env python
# encoding: utf-8

from __future__ import division #to make the python do the real division
import os

def Classify(value):
    if value > 90:
        return 'A'
    if value > 80:
        return 'B'
    if value > 70:
        return 'C'
    if value > 60:
        return 'D'
    else:
        return 'F'

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            str_mark = f.read()
            lst_mark = str_mark.split()
            lst_fmark = [float(i) for i in lst_mark]
            lst_fmark.sort()
            sum_lst = sum(lst_fmark)
            avg_lst = sum_lst/len(lst_fmark)
            print "the average grade is %0.2f" %avg_lst
            class_lst = [Classify(i) for i in lst_fmark]
            print class_lst

9_6

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F1 = raw_input('Please input the file name: ')
    F2 = raw_input('Please input another file name: ')
    file_path1 = FilePathCheck(F1)
    file_path2 = FilePathCheck(F2)
    if file_path1 and file_path2:
        with open(file_path1) as f1:
            with open(file_path2) as f2:
                line1 = f1.readlines()
                line2 = f2.readlines()
                for i in range(min(len(line1), len(line2))):
                    if line1[i] == line2[i]:
                        continue
                    else:
                        print 'The different line is %s' %(i+1)
                        break
                else:
                    print 'All lines are the same'

9_8

#/usr/bin/python2
# coding: utf-8

if __name__ == '__main__':
    module = raw_input('Please input a module name: ')
    mod = __import__(module)
    dir_mod = dir(mod)
    print dir_mod
    for i in dir_mod:
        print 'name: %s' %i
        print 'type: %s' %type(getattr(mod, i))
        print 'value: %s' %getattr(mod, i)
        print 

9_9

import os
pymodules = {}
path = r'/usr/lib/python2.7'
pyfiles = [f for f in os.listdir(path) if f.endswith('.py')]
for f in pyfiles:
    module = f[:-3]
    pymodules.setdefault(module, '')
    pyfile = path + os.sep + f
    fobj = open(pyfile)
    doc = False
    for line in fobj:
        if line.strip().startswith('"""''"""')and line.strip().endswith('"""'):
            pymodules[module] += line
            fobj.close()
            break
        elif (line.strip().startswith('"""''"""') or line.strip().startswith('r"""')) and len(line)>3:
            doc = True
            pymodules[module] += line
            continue
        elif doc:
            if line == '"""':
                pymodules[module] += line
                fobj.close()
                doc = False
                break
            else:
                pymodules[module] += line
        else:
            continue
    else:
        fobj.close()
hasdoc = []
nodoc = []
for module in pymodules:
    if pymodules[module]:
        hasdoc.append(module)
    else:
        nodoc.append(module)

print 'module has no doc:'
for key in nodoc:
    print key
print '\n'
print 'module has doc:'
for key in hasdoc:
    print 'module:', key
    print 'doc:', pymodules[key]

9_10

這個題目寫的規模比較大,主要原因是自己花了3個晚上的時間來學習wxPython的GUI使用(白天要在實驗室弄實驗室專案(與python無關),忙成狗,實在沒辦法寫python)。總體來講這個圖形介面的模組不難入門,用起來也比Tkinter這個模組更舒服些。之所以放棄已經初步瞭解的Tkinter,改投wxpython,是因為wxPython使用的人多一些,無論是基礎的教程還是排異解難都要方便些,為了提早出坑,所以才開始學習wxPython。想自己瞭解wxPython的可以訪問http://wiki.wxpython.org/Getting%20Started#Getting_started_with_wxPython
wxPython的安裝,linux下可以使用 sudo apt-get install python-wxtools, windows沒查過,教程也很多。
現在初步瞭解了幾個控制元件的使用,但是具體的排版和編輯還是差強人意,請忽略我糟糕的審美,畢竟我的美術是體育老師教的。(這年頭教體育背鍋上萬噸)

#!/usr/bin/env python
# coding: utf-8

import wx
import os
class BankFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(500,100))
        # 建立分頁
        self.nb = wx.Notebook(self)

        # 建立儲蓄
        self.panel_depos = wx.Panel(self.nb)
        sizer_depos = wx.BoxSizer(wx.VERTICAL)
        self.button_dep_save = wx.Button(self.panel_depos
                                         , label="Save")
        self.button_dep_withdraw = wx.Button(self.panel_depos
                                             , label="Withdraw")
        sizer_depos.Add(self.button_dep_save, 1, wx.EXPAND)
        sizer_depos.Add(self.button_dep_withdraw, 1, wx.EXPAND)
        self.panel_depos.SetSizerAndFit(sizer_depos)
        self.Bind(wx.EVT_BUTTON, self.OnSave, self.button_dep_save)
        self.Bind(wx.EVT_BUTTON, self.OnWithdraw, self.button_dep_withdraw)

        # 建立金融市場
        self.panel_finan = wx.Panel(self.nb)
        sizer_finan = wx.BoxSizer(wx.VERTICAL)
        self.button_fin_borrow = wx.Button(self.panel_finan,
                                           label="Borrow")
        self.button_fin_loan = wx.Button(self.panel_finan,
                                         label="Loan")
        sizer_finan.Add(self.button_fin_borrow, 1, wx.EXPAND)
        sizer_finan.Add(self.button_fin_loan, 1, wx.EXPAND)
        self.panel_finan.SetSizerAndFit(sizer_finan)

        # 將介面放到分頁中
        self.nb.AddPage(self.panel_depos, "Deposite")
        self.nb.AddPage(self.panel_finan, "Financial Market")

    def OnSave(self, event):
        self.Hide()     # 隱藏主介面
        self.text = "0" # 初始化資料

        # 讀取資訊
        file_name = "deposit.txt"
        f = FileExist(file_name, 'r')
        lst_data = f.readlines()
        f.close()
        self.sum_of_depos = float(lst_data[len(lst_data)-1].strip())

        # 設定介面
        self.frame_save = wx.Frame(None, title="Save")
        quote_msg = wx.StaticText(self.frame_save, label="Your bank acount has %s yuan left"
                                  %self.sum_of_depos)
        quote_save = wx.StaticText(self.frame_save, label="How much do you want to save?")
        text_save = wx.TextCtrl(self.frame_save, size = (100, 20))
        button_save = wx.Button(self.frame_save, label="OK")
        save_sizer = wx.BoxSizer(wx.VERTICAL)
        save_sizer.Add(quote_msg, wx.EXPAND)
        save_sizer.Add(quote_save, wx.EXPAND)
        save_sizer.Add(text_save, wx.EXPAND)
        save_sizer.Add(button_save, wx.EXPAND)
        self.frame_save.SetSizerAndFit(save_sizer)
        self.frame_save.Show()

        # 設定響應
        self.frame_save.Bind(wx.EVT_BUTTON, self.Save, button_save)
        self.frame_save.Bind(wx.EVT_TEXT, self.EvtText, text_save)

    def OnWithdraw(self, event):
        self.Hide()
        self.text = "0"

        file_name = "deposit.txt"
        f = FileExist(file_name, 'r')
        lst_data = f.readlines()
        f.close()
        self.sum_of_depos = float(lst_data[len(lst_data)-1].strip())

        self.frame_withdraw = wx.Frame(None, title="Withdraw")
        quote_msg = wx.StaticText(self.frame_withdraw, label="Your bank acount has %s yuan left"
                                  %self.sum_of_depos)
        quote_withdraw = wx.StaticText(self.frame_withdraw, label="How much do you want to withdraw?")
        text_withdraw = wx.TextCtrl(self.frame_withdraw, size = (100, 20))
        button_withdraw = wx.Button(self.frame_withdraw, label="OK")
        withdraw_sizer = wx.BoxSizer(wx.VERTICAL)
        withdraw_sizer.Add(quote_msg, wx.EXPAND)
        withdraw_sizer.Add(quote_withdraw, wx.EXPAND)
        withdraw_sizer.Add(text_withdraw, wx.EXPAND)
        withdraw_sizer.Add(button_withdraw, wx.EXPAND)
        self.frame_withdraw.SetSizerAndFit(withdraw_sizer)
        self.frame_withdraw.Show()

        # 設定響應
        self.frame_withdraw.Bind(wx.EVT_BUTTON, self.Withdraw, button_withdraw)
        self.frame_withdraw.Bind(wx.EVT_TEXT, self.EvtText, text_withdraw)

    def Save(self, event):
        self.frame_save.Close(True)
        self.Show()
        amount = float(self.text.strip())
        self.sum_of_depos += amount
        f = FileExist("deposit.txt", "a")
        f.write("%s\n" %self.sum_of_depos)
        f.close()

    def Withdraw(self, event):
        self.frame_withdraw.Close(True)
        self.Show()
        amount = float(self.text.strip())
        if self.sum_of_depos > amount:
            self.sum_of_depos -= amount
            f = FileExist("deposit.txt", "a")
            f.write("%s\n" %self.sum_of_depos)
            f.close()
        else:
            dlg = wx.MessageDialog(self, "Warning", "You don't have enough deposite", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()


    def EvtText(self, event):
        self.text = event.GetString()

def FileExist(file_name, mode):
    curdir = os.getcwd()
    path = os.path.join(curdir, file_name)
    if (not os.path.isfile(path)):
        f = open(path, "w")
        f.write("0\n")
        f.close()
    f = open(path, mode)
    return f


app = wx.App(False)
frame = BankFrame(None, "Family Account")
frame.Show()
app.MainLoop()

9_11

#!/usr/bin/env python
# coding: utf-8

import wx
import os

class URLFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title)
        file_name = "9_11url.html"
        self.FileCreate(file_name)

        self.nb = wx.Notebook(self)
        # add url panel
        self.add_panel = wx.Panel(self.nb)
        grid = wx.GridBagSizer(hgap=3, vgap=4)
        hSizer = wx.BoxSizer(wx.VERTICAL)
        # add txt blank
        self.lbl_name = wx.StaticText(self.add_panel, label="name")
        self.lbl_url = wx.StaticText(self.add_panel, label="url")
        self.lbl_remark= wx.StaticText(self.add_panel, label="remark")
        self.ctrl_name = wx.TextCtrl(self.add_panel, size = (50, 20))
        self.ctrl_url = wx.TextCtrl(self.add_panel, size=(150, 20))
        self.ctrl_remark = wx.TextCtrl(self.add_panel, size=(100, 20))
        # grid operation
        grid.Add(self.lbl_name, pos=(0,0))
        grid.Add(self.lbl_url, pos=(0,1))
        grid.Add(self.lbl_remark, pos=(0,2))
        grid.Add(self.ctrl_name, pos=(1,0))
        grid.Add(self.ctrl_url, pos=(1,1))
        grid.Add(self.ctrl_remark, pos=(1,2))
        grid.Add((3,2), pos=(2,0))
        # sizer operation
        self.button_add = wx.Button(self.add_panel, label="Add")
        hSizer.Add(grid, 4, wx.ALL, 9)
        hSizer.Add(self.button_add, 1, wx.CENTER)
        self.add_panel.SetSizerAndFit(hSizer)
        self.nb.AddPage(self.add_panel, "Add Url")

        # edit url panel
        self.edit_panel = wx.Panel(self.nb)
        with open(self.path, "r") as f:
            self.lst_urlmsg = f.read().split(r"\n")
            self.len_url = len(self.lst_urlmsg)
        grid_edit = wx.GridBagSizer(hgap=3, vgap=self.len_url)
        hSizer_edit = wx.BoxSizer(wx.VERTICAL)
        self.name_lst = []
        self.url_lst = []
        self.remark_lst = []
        lst_msg=[]
        for i, urlmsg in enumerate(self.lst_urlmsg):
            if urlmsg=="":
                continue
            lst_msg = urlmsg.split(",")
            str_name = lst_msg[0]
            str_url = lst_msg[1]
            str_remark = lst_msg[2]
            ctrl_name = wx.TextCtrl(self.edit_panel, size=(50, 20))
            ctrl_name.AppendText(str_name)
            ctrl_url = wx.TextCtrl(self.edit_panel, size=(150, 20))
            ctrl_url.AppendText(str_url)
            ctrl_remark = wx.TextCtrl(self.edit_panel, size=(100, 20))
            ctrl_remark.AppendText(str_remark)
            grid_edit.Add(ctrl_name, pos=(i,0))
            grid_edit.Add(ctrl_url, pos=(i,1))
            grid_edit.Add(ctrl_remark, pos=(i,2))
            self.name_lst.append(ctrl_name)
            self.url_lst.append(ctrl_url)
            self.remark_lst.append(ctrl_remark)
        self.button_edit = wx.Button(self.edit_panel, label="Edit")
        hSizer_edit.Add(grid_edit, 0, wx.ALL)
        hSizer.Add(self.button_edit, 1, wx.CENTER);
        self.edit_panel.SetSizerAndFit(hSizer_edit)
        self.nb.AddPage(self.edit_panel, "Edit Url")

        self.Bind(wx.EVT_BUTTON, self.Add, self.button_add)
        self.Bind(wx.EVT_BUTTON, self.Edit, self.button_edit)

    def Add(self, event):
        str_name = self.ctrl_name.GetValue().strip()
        str_url = self.ctrl_url.GetValue().strip()
        str_remark = self.ctrl_remark.GetValue().strip()
        with open(self.path, "a") as f:
            if str_name!="" and str_url!="":
                f.write(r"%s,%s,%s\n" %(str_name, str_url, str_remark))

    def Edit(self, event):
        num = len(self.name_lst)
        with open(self.path, "w") as f:
            for i in range(num):
                str_name = self.name_lst[i].GetValue().strip()
                str_url = self.name_lst[i].GetValue().strip()
                str_remark = self.remark_lst[i].GetValue().strip()
                f.write(r"%s,%s,%s\n" %(str_name, str_url, str_remark))

    def FileCreate(self, file_name):
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        if (not os.path.isfile(self.path)):
            f = open(self.path, "w")
            f.close()

app = wx.App(False)
frame = URLFrame(None, "URL Management System")
frame.Show()
app.MainLoop()

9_12

這段程式碼寫起來倒是不難,可是為了定位錯誤原因,花了我整整一個晚上的時間。利用cPickle每次資料都沒有儲存起來,無論怎麼讀,都是空,真是折騰死了。
最後成功定位原因:在函式中,我定義了g_users這個全域性變數,於是我就在各個class裡面自然而然用了c++的邏輯到處使用了。但python其實此時是建立了局部的變數,所以我的傳值一直不成功,才導致了這個問題。
最後得到的經驗教訓是:
全域性變數記得加global
全域性變數記得加global
全域性變數記得加global

#!/usr/bin/python
# coding: utf-8

import wx
import os
import cPickle
import string

availChar = string.lowercase + string.uppercase
g_path = ''
g_users = {}


class AccountFrame(wx.Frame):
    def __init__(self, parent, title):
        global g_path
        global g_users
        wx.Frame.__init__(self, parent, title=title, size=(200, 200))
        file_name = "9_12_Account.txt"
        #self.FileCreate(file_name)
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        g_path = self.path
        f = open(self.path, 'r')
        self.users = cPickle.load(f)
        f.close()
        g_users = self.users
        self.btn_log = wx.Button(self, label="user loggin")
        self.btn_show = wx.Button(self, label="Show all users")
        self.btn_del = wx.Button(self, label="Delete user")
        self.btn_quit = wx.Button(self, label="Quit")
        hSizer = wx.BoxSizer(wx.VERTICAL)
        hSizer.Add(self.btn_log, 1, wx.CENTER)
        hSizer.Add(self.btn_show, 1, wx.CENTER)
        hSizer.Add(self.btn_del, 1, wx.CENTER)
        hSizer.Add(self.btn_quit, 1, wx.CENTER)
        self.SetSizerAndFit(hSizer)

        self.Bind(wx.EVT_BUTTON, self.Loggin, self.btn_log)
        #self.Bind(wx.EVT_BUTTON, self.Show, self.btn_show)
        #self.Bind(wx.EVT_BUTTON, self.Delete, self.btn_del)
        self.Bind(wx.EVT_BUTTON, self.Quit, self.btn_quit)
        self.Bind(wx.EVT_CLOSE, self.Quit, self)

    def Loggin(self, event):
        self.Hide()
        LogginFrame(self)
    def Quit(self, event):
        global g_users
        f = open(self.path, 'w')
        cPickle.dump(g_users, f, 0)
        f.close()
        self.Destroy()



    def FileCreate(self, file_name):
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        g_path = self.path
        if (not os.path.isfile(self.path)):
            f = open(self.path, "wb")
            f.close()
class LogginFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=None, title="Loggin")
        global g_users
        self.parent = parent
        self.txt_name = wx.StaticText(self, label="Name:", size=(80,30))
        self.txt_passwd = wx.StaticText(self, label="Password:",size=(80,30))
        self.ctrl_name = wx.TextCtrl(self, size=(150,30))
        self.ctrl_passwd = wx.TextCtrl(self, size=(150,30))
        self.btn_ok = wx.Button(self, label="Ok")
        grid_log = wx.GridBagSizer(hgap=2, vgap=4)
        grid_log.Add(self.txt_name, pos=(0,0))
        grid_log.Add(self.ctrl_name, pos=(0,1))
        grid_log.Add(self.txt_passwd, pos=(1,0))
        grid_log.Add(self.ctrl_passwd, pos=(1,1))
        hSizer = wx.BoxSizer(wx.VERTICAL)
        hSizer.Add(grid_log, 4, wx.ALL, 2)
        hSizer.Add(self.btn_ok, 1, wx.EXPAND)
        self.SetSizerAndFit(hSizer)

        self.Bind(wx.EVT_BUTTON, self.Ok, self.btn_ok)
        self.Bind(wx.EVT_CLOSE, self.Quit, self)
        self.Show()
    def Quit(self, event):
        self.parent.Show()
        self.Destroy()


    def Ok(self, event):
        global g_users
        name = self.ctrl_name.GetValue()
        password = self.ctrl_passwd.GetValue()
        bNameOk = True
        for i in name:
            if i not in availChar:
                bNameOk = False
                break
        if not bNameOk:
            dlg = wx.MessageDialog(self, "Not a available name", "warning", wx.OK)
        elif name in g_users.keys():
            if password == g_users[name]:
                dlg = wx.MessageDialog(self, "welcome back", "info", wx.OK)
            else:
                dlg = wx.MessageDialog(self, "password not correct", "warning", wx.OK)
        else:
            g_users[name] = password

            dlg = wx.MessageDialog(self, name, password, wx.OK)
        dlg.ShowModal()
        dlg.Destroy()
        self.parent.Show()
        self.Destroy()




if __name__ == "__main__":
    app = wx.App(False)
    frame = AccountFrame(None, "Loggin System")
    frame.Show()
    app.MainLoop()

#9_13

#!/usr/bin/python
# coding: utf-8

import sys
if __name__ == "__main__":
    argvs = sys.argv
    print "all the argvs are: ",
    for i in argvs:
        print i,

9_14

#!/usr/bin/python
# coding: utf-8

from __future__ import division
import sys

if __name__ == "__main__":
    argv = sys.argv
    math = []
    for i in range(1, len(argv)):
        math.append(argv[i])
    str_math = ''.join(math)
    b_math = True
    for i in "+-*/^":
        if i in str_math:
            break
    else:
        b_math = False
    if b_math:
        ab = str_math.split(i)
        a = float(ab[0])
        b = float(ab[1])
        if i is "+":
            print a+b
        elif i is "-":
            print a-b
        elif i is "*":
            print a*b
        elif i is "/":
            print a/b
        else:
            print a**b

9_15

#!/usr/bin/python
# coding: utf-8

import sys
import os

if __name__ == "__main__":
    argv = sys.argv
    if len(argv) != 3:
        print "not right parameters"
        os._exit(1)
    file1 = argv[1]
    file2 = argv[2]
    curdir = os.getcwd()
    path1 = os.path.join(curdir, file1)
    path2 = os.path.join(curdir, file2)
    with open(path1, 'r') as f1:
        with open(path2, 'w') as f2:
            data = f1.read()
            f2.write(data)
    print "copy finished"

9_16

#!/usr/bin/python
# coding: utf-8

def check_text():
    """文件處理函式,對長度超過80的進行截斷"""
    f = open("1.txt", "r")
    lines_1 = f.readlines()
    f.close()
    lines_2 = [] #將新生成的文件先儲存在lines_2中
    for line in lines_1:
        if len(line)>80:
            if line[80] == " ": #如果81個位置是空格,就不需要考慮單詞邊界問題
                lines_2.append(line[:80]+"n")
                lines_2.append(line[81:])
            else:
                local = line[:80].rfind(" ") #否則查詢最靠近第80個位置的空格截斷,保持單詞的完整性
                lines_2.append(line[:local]+"n")
                lines_2.append(line[local+1:])
        else:
            lines_2.append(line)
    f = open("1.txt", "w")
    f.writelines(lines_2)
    f.close()

if __name__ == "__main__":
    """主函式"""
    while True: #迴圈檢測每行的長度,直至長度全部小魚或等於80
        f = open("1.txt", "r")
        lines = f.readlines()
        f.close()
        for line in lines:
            if len(line)>80:
                check_text()
                break
        else:
            break
    print "Done!"

9_17

#!/usr/bin/python
# coding: utf-8

import os
def Create():
    """Create a file"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    f = open(path, "w")
    file_content = []
    print "Please input file content, press Ctrl + d to stop: "
    while True:
        try:
            f.write(raw_input()+"\n")
        except (EOFError, KeyboardInterrupt, IndexError):
            f.close()
            break

def Show():
    """Show the content on the screen"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    f = open(path, "r")
    for line in f:
        print line,
    f.close()

def Edit():
    """Edit a file content"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    with open(path, "r") as f:
        lines = f.readlines()
    row_number = int(raw_input("Please input the row number: "))
    row_content = raw_input("Please edit content: ") + "\n"
    lines[row_number-1] = row_content
    with open(path, "w") as f:
        for line in lines:
            f.write(line)

def Menu():
    CMD = {"c": Create, "s": Show, "e": Edit}
    msg_help = """Please choose:
(C)reate
(S)how
(E)dit
(Q)uit"""
    print msg_help
    msg = "Your choice: "
    while True:
        try:
            choice = raw_input(msg).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = 'q'
        if choice not in "cseq":
            msg = "Wrong choice, input again: "
            continue
        else:
            break
    if choice is not "q":
        CMD[choice]()

if __name__ == "__main__":
    Menu()

9_18

#!/usr/bin/python
# coding:utf-8

import os

def count(path, ord_of_str):
    sum_of_str = 0
    str_to_find = chr(ord_of_str)
    with open(path) as f:
        for line in f:
            sum_of_str += line.count(str_to_find)
    return sum_of_str

if __name__ == "__main__":
    cur_dir = os.getcwd()
    file_name = raw_input("Please input a file name: ")
    path = os.path.join(cur_dir, file_name)
    ord_of_str = int(raw_input("Please input a number: "))
    sum_of_str = count(path, ord_of_str)
    print "the string used %s times" %sum_of_str

9_19

#!/usr/bin/python
# coding:utf-8

import os

def count(path, ord_of_str):
    sum_of_str = 0
    str_to_find = chr(ord_of_str)
    with open(path) as f:
        for line in f:
            sum_of_str += line.count(str_to_find)
    return sum_of_str

if __name__ == "__main__":
    cur_dir = os.getcwd()
    file_name = raw_input("Please input a file name: ")
    path = os.path.join(cur_dir, file_name)
    ord_of_str = int(raw_input("Please input a number: "))
    sum_of_str = count(path, ord_of_str)
    print "the string used %s times" %sum_of_str

9_20

這個程式很簡單,我就不多做介紹了,隨便一搜就能找到gzip的資料。

#!/usr/bin/python
# coding:utf-8

import gzip
import os

def gz(file_name):
    """gzip a file at the current work directory"""
    curdir = os.getcwd()
    path = os.path.join(curdir, file_name)
    g_file_name = file_name + ".gz"
    g_file = gzip.GzipFile(g_file_name, "wb")
    print g_file_name
    g_file.write(open(path).read())
    g_file.close()

def ungz(g_file_name):
    """ungzip a file"""
    g_file_name_tuple = os.path.splitext(g_file_name)
    file_name = g_file_name_tuple[0]
    g_file = gzip.GzipFile(g_file_name)
    open(file_name, "w+").write(g_file.read())
    g_file.close()

if __name__ == "__main__":
    CMDS = {"g": gz, "u" : ungz}
    msg_help = """(G)zip
(U)ngzip 
(Q)uit

Please choose: """
    while True:
        try:
            choice = raw_input(msg_help).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = 'q'
        if choice not in "guq":
            msg_help = "Wrong choice, please input again: "
        else:
            break
    if choice != 'q':
        file_name = raw_input("Input a file name: ")
        CMDS[choice](file_name)

9_21

#!/usr/bin/python
# coding: utf-8

import zipfile
import os

def CreateZipFile(z_file_name):
    """Create a zip file
    z_file_name: zipfile's name"""
    curdir = os.getcwd()
    path = os.path.join(curdir, z_file_name)
    file_name = raw_input("Input a file name: ")
    file_path = os.path.join(curdir,file_name)
    z_file = zipfile.ZipFile(path, "w")
    z_file.write(file_path, file_name, zipfile.ZIP_DEFLATED)
    z_file.close()

def ExtraZipFile(z_file_name):
    """Extract a zip file"""
    curdir = os.getcwd()
    path = os.path.join(curdir, z_file_name)
    z_file = zipfile.ZipFile(path)
    for file in z_file.namelist():
        z_file.extract(file, curdir)
    z_file.close()

if __name__ == "__main__":
    msg_help = """(C)reate a zip file
(E)xtract a zip file
(Q)uit

Please choose: """
    CMDs = {"c" : CreateZipFile, "e" : ExtraZipFile}
    while True:
        try:
            choice = raw_input(msg_help).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = "q"
        if choice not in "ceq":
            msg_help = "Wrong input, try again: "
            continue
        else:
            break
    if choice is not "q":
        file_name = raw_input("Input a zip file name: ")
        CMDs[choice](file_name)