Python核心编程v2.0 第9章习题答案(下)

12.
a)过程中还是沿用的db进行处理,开始和结束用文件生成及读取db

# -*- coding: utf-8 -*-
#coding = utf-8
import time
db = {}

#从文件中读取用户信息
def readfile():
    name = raw_input('filename:')
    f = open(name,'r')
    for eachline in f:
        #去掉最后的换行,否则会多出一个为空的用户
        eachline = eachline.rstrip()
        li = eachline.split(':')
        infor = []
        infor.append(li[1])
        infor.append(li[2])
        db[li[0]]=infor

#将db写入文件
def writefile():
    name = raw_input('filename for write:')
    f = open(name,'w')
    for keys in db:
        f.write(keys+':')
        f.write(str(db[keys][0])+':')
        f.write(str(db[keys][1])+'\n')
    f.close()

def newuser():
    prompt = 'login desired:'
    while True:
        name = raw_input(prompt)
        if db.has_key(name):
            prompt = 'name taken,try another'
            continue
        else:
            break
    pwd = raw_input('passwd:')
    #存下新用户第一次登录时间
    db[name] = [pwd,time.strftime("%Y %m %d %H %M", time.localtime())]

def olduser():
    name = raw_input('login:')
    pwd = raw_input('passwd:')
    passwd = db[name][0]
    if passwd == pwd:
        print 'welcome back',name
        #记录登录时间
        ti = time.strftime("%Y %m %d %H %M", time.localtime())
        lis1 = ti.split(' ')
        lis2 = db[name][1].split(' ')
        # print lis1
        # print lis2
        #打印上次登录时间
        print 'you alraedy logged in at %s' %db[name][1]
        #更新登录时间
        db[name][1] = ti
    else:
        print 'login incorrect'

def delete():
    name = raw_input('you want to delete')
    del db[name]
    print '%s has been delet'% name

def showuser():
    for key in db:
        print key,
        print db[key][0],
        print db[key][1]

def showmenu():
    readfile()
    prompt = '''
    N
    E
    Q
    D
    S
    enter choice:
    '''

    done = False
    while not done:
        chosen = False
        while not chosen:
            try :
                choice = raw_input(prompt).strip()[0]
            except(EOFError,KeyboardInterrupt):
                choice = 'Q'
            print 'you picked :[%s]' % choice
            if choice not in 'NEQDS':
                print 'invaild option'
            else:
                chosen = True

        if choice == 'Q':done = True
        if choice == 'N':newuser()
        if choice == 'E':olduser()
        if choice == 'D':delete()
        if choice == 'S':showuser()
    writefile()

if __name__ == '__main__':
    showmenu()

b)
只贴了有改动部分。

...
import pickle

#从文件中读取用户信息
def readfile():
    name = raw_input('filename:')
    f = open(name,'r')
    global db
    db = pickle.load(f)
    f.close()

#将db写入文件
def writefile():
    name = raw_input('filename for write:')
    f = open(name,'w')
    pickle.dump(db,f)
    f.close()

c)
在设置了writeback为True的情况下,当db更改后,会自动的写入缓存,关闭后写入文件中,可以去掉writefile函数

#从文件中读取用户信息
def readfile():

    name = raw_input('filename:')
    global db
    db = shelve.open(name,writeback=True)

13.
命令行参数是调用某个程序时除程序名以外的其他参数。pycharm下在terminal窗口调用python filename name1 name2 name3可以使用

    print 'you entered',len(sys.argv),'arguments'
    print 'they are',str(sys.argv)

结果

D:\pycharm\LanguageStudy>python langstudy.py name1 name2 name3
you entered 4 arguments
they are ['langstudy.py', 'name1', 'name2', 'name3']

14.

# -*- coding: utf-8 -*-
#coding = utf-8

from __future__ import division
import sys

record = ''

def count(list) :
    list[0] = int(list[0])
    list[2] = int(list[2])
    if list[1] == '+' :
        r = list[0]+list[2]
    elif list[1] == '-' :
        r = list[0]-list[2]
    else:
        print "wrong operator"
    return r

def writefile():
    f = open('ar.txt','w')
    f.write(record)
    f.close()

def showinscreen():
    f = open('ar.txt','r')
    for eachline in f:
        print eachline.rstrip()
    f.close()
    f = open('ar.txt','w')
    f.close()


if __name__ == '__main__':

    if len(sys.argv ) == 4:
        list = []
        list.append(sys.argv[1])
        list.append(sys.argv[2])
        list.append(sys.argv[3])
        record = record+sys.argv[1]+sys.argv[2]+sys.argv[3]+'\n'
        result = count(list)
        record = record + str(result)+'\n'
        print result
        writefile()
    elif sys.argv[1] == 'print':
        showinscreen()

15.

def copy(name1,name2):
    fin = open(name1,'r')
    content = fin.readlines()
    fin.close()
    fout = open(name2,'a')
    #追加模式打开后,指针还是在文件开头位置,需要位移到文件末尾进行添加
    fout.seek(0,2)
    for i in content:
        fout.write(i)
    fout.close()


if __name__ == '__main__':

    name1 = raw_input('name1:')
    name2 = raw_input('name2:')
    copy(name1,name2)

16.
读文件时候的指针有点不好控制,写了一个复杂度高一些的实现方法,先读出来处理后再写入

# -*- coding: utf-8 -*-
#coding = utf-8

def nomorethan10(name1):
    f = open(name1,'r')
    linelist = []
    for eachline in f:
        if len(eachline)>10:
            index1 = eachline.rfind(' ',0,10)
            index2 = eachline.find(' ',10,len(eachline)-1)
            if 10 - index1> index2-10:
                line = eachline[0:index2]+'\n'+eachline[index2:]
            else:
                line = eachline[0:index1]+'\n'+eachline[index1:]

            linelist.append(line.rstrip('\n'))
        else:
            line = eachline
            linelist.append(line)
    f.close()
    f = open(name1,'w')
    for i in linelist:
        f.write(i+'\n')
    f.close()



if __name__ == '__main__':

    name1 = raw_input('name:')
    nomorethan10(name1)

17.
没写GUI,大概写了写逻辑

# -*- coding: utf-8 -*-
#coding = utf-8
import sys


def creatfile(name,contlis):
    f = open(name,'w')
    for i in contlis:
        f.write(i)
        f.write('\n')
    f.close()

def showfile():
    for i in lines:
        print i.rstrip()

def editfile(number):
    f = open(name,'r')
    lines = f.readlines()
    f.close()
    line = lines[number-1]
    print line
    line = raw_input('input your new line')
    lines[number-1] = line.rstrip()
    return lines

def savefile():
    f = open(name,'w')
    for i in lines:
        f.write(i)
    f.close()

if __name__ == '__main__':
    while True:
        print 'crear file:c'
        print 'show file:s'
        print 'edit file:e'
        print 'save file:a'
        print 'quit:q'
        order = raw_input('order:')
        if order == 'c':
            name = raw_input('name:')
            content = raw_input('content:')
            contlis = content.split('.')
            lines = contlis
            creatfile(name,contlis)

        elif order == 's':
            showfile()

        elif order == 'e':
            number = int(raw_input('line number:'))
            lines = editfile(number)

        elif order == 'a':
            savefile()

        elif order == 'q':
            break

18.

# -*- coding: utf-8 -*-

def checkchar(char,name):
    f = open(name,'r')
    index = 0
    for eachline in f:
        count = eachline.count(char)
        index = index+count
    f.close()
    return index


if __name__ == '__main__':
    num = int(raw_input('input a number'))
    char = chr(num)
    name = raw_input('name')
    print checkchar(char,name)

19.
f.write函数写入后会覆盖后一个字节,所以先用list存了一下生成的数据在写入

# -*- coding: utf-8 -*-
import  random

def creatfile(char,number,lenth):
    ls = []
    i = 0
    while i< lenth - number:
        ran = random.randint(0,255)
        if chr(ran) == char:
            ran = ran+1
        ls.append(chr(ran))
        i = i+1
    for j in range(number):
        ranlen = random.randint(0,lenth)
        ls.insert(ranlen,char)

    f = open(name,'wb')
    for i in ls:
        f.write(i)
    f.close()



if __name__ == '__main__':
    num = int(raw_input('input a number'))
    char = chr(num)
    name = raw_input('name')
    creatfile(char,2,5)

20.

# -*- coding: utf-8 -*-
import  gzip

def makezip(name,zipname):
    f_in = open(name, 'rb')
    f_out = gzip.open(zipname, 'wb')
    f_out.writelines(f_in)
    f_out.close()
    f_in.close()

def readzip(zipname):
    f_in = gzip.open(zipname, 'rb')
    file_content = f_in.read()
    f_out = open('tr.txt','wb')
    f_out.write(file_content)
    f_in.close()
    f_out.close()

if __name__ == '__main__':
    name = 'ar.txt'
    zipname = 'ar.gz'
    makezip(name,zipname)
    readzip(zipname)

21.
创建和添加是一样,只是mode一个为’w’一个为’a’和普通文件相同。sys.path[0]为调用该py程序的目录。

# -*- coding: utf-8 -*-
import zipfile
import sys


def addzip(file2):
    f = zipfile.ZipFile(name, 'a', zipfile.ZIP_DEFLATED)
    f.write(file2)
    f.close()

def readzip(file2):
    f = zipfile.ZipFile(name, 'r')
    f.extract(file2,sys.path[0])
    f.close()

if __name__ == '__main__':
    name = 'ar.zip'
    file = 'ar.txt'
    file2 = 'tr.txt'
    addzip(file2)
    readzip(file2)

22.
zipfile返回的date_time属性为6元元组,time.mktime接收9元,补充了3个0

# -*- coding: utf-8 -*-
import zipfile
import time

add = [0,0,0]

def readzip(file):
    zp = zipfile.ZipFile(file,'r')
    for file in zp.namelist():
        info = zp.getinfo(file)
        print file
        print info.compress_size,
        print info.file_size
        print info.file_size/info.compress_size
        print info.date_time
        ti  = list(info.date_time)
        ti.extend(add)
        secs = time.mktime(ti)
        time_a = time.ctime(secs)
        print time_a
if __name__ == '__main__':
    readzip('tr.zip')



23.
tarfile的open函数可以选择不同模式,在模式中已经实现了对gzip和bzip2的支持。’w’模式再次打开后写入会覆盖,’a’模式不可以加压缩参数,如果需要添加,比较麻烦的思路是解压,再全部写进去一次。’a’模式对gzip好后的文件也做不进去添加。
在这里贴一下模式列表:

'r' or 'r:*'   Open for reading with transparent compression (recommended).
'r:'   Open for reading exclusively without compression.
'r:gz'   Open for reading with gzip compression.
'r:bz2'   Open for reading with bzip2 compression.
'a' or 'a:'   Open for appending with no compression. The file is created if it does not exist.
'w' or 'w:'   Open for uncompressed writing.
'w:gz'   Open for gzip compressed writing.
'w:bz2'   Open for bzip2 compressed writing.
# -*- coding: utf-8 -*-
import tarfile
import sys


def addzip(file2):
    f = tarfile.open(name,'w:gz')
    f.add(file2)
    f.close()

def readzip(file2):
    f = tarfile.open(name,'r:gz')
    f.extract(file2,sys.path[0])
    f.close()

if __name__ == '__main__':
    name = 'ar.tar'
    file = 'ar.txt'

    addzip(file)
    readzip(file)

24.
实现了tar转移到zip,反过来思路类似。生成了中间文件。

# -*- coding: utf-8 -*-
import tarfile
import zipfile
import sys



def readtar(file2):
    f = tarfile.open('ar.tar','r:gz')
    if file2 in f.getnames():
        f.extract(file2,sys.path[0])
    else:
        fc = open(file2,'w')
        fc.close()

    f.close()

def addzip(file2):
    f = zipfile.ZipFile('br.zip', 'a', zipfile.ZIP_DEFLATED)
    f.write(file2)
    print f.namelist()
    f.close()

def move(name):
    readtar(name)
    addzip(name)

if __name__ == '__main__':
    move('haha.txt')

25.
题目的意思就是第一个输入的压缩文件直接解压到提供的目录,然后后面的压缩文件在该目录下创建同名文件夹,再解压到同名文件夹里面

# -*- coding: utf-8 -*-
import tarfile
import sys
import os
import zipfile


def readzip(name,di):
    f = zipfile.ZipFile(name, 'r')
    for i in f.namelist():
        f.extract(i,di)
    f.close()

def readtar(name,di):
    f = tarfile.open(name,'r:gz')
    for i in f.getnames():
        f.extract(i,di)
    f.close()

def makefile(lis,di):
    if lis[0].endswith('.zip'):
        readzip(lis[0],di)
    elif  lis[0].endswith('.tar'):
        readtar(lis[0],di)

    i = 1
    while i <len(lis):
        index = lis[i].index('.')
        name = lis[i][0:index]
        di_n = di+'\\'+name
        os.mkdir(di_n)
        if lis[i].endswith('.zip'):
            readzip(lis[i],di_n)
        elif lis[i].endswith('.tar'):
            readtar(lis[i],di_n)
        i = i+1



if __name__ == '__main__':
    lis = ['ar.zip','sr.zip','dr.tar']
    di = sys.path[0]
    makefile(lis,di)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值