《python核心编程》第九章习题

9-6:

path1 = 'text1.txt'
path2 = 'text2.txt'

fopen1 = open(path1, 'r')
fopen2 = open(path2, 'r')

iter1 = iter(fopen1)
iter2 = iter(fopen2)
cow = 0
while True:
    try:
        line1 = iter1.next()
        line2 = iter2.next()
        for column in range(len(line1)):
            if (line1[column] != line2[column]):
                print "%s: (%i,%i)" % ("unequal location", cow, column)
        cow += 1
    except StopIteration:
        break

 

9-7:

import os

pathname = os.getcwd()
basename = 'setting.ini'
path = os.path.join(pathname, basename)
file = open(path, 'r')
file.seek(0)

for f in file:
    if f[0] == "[":
        title = f[1:-2]
        print "title is: " + title
    else:
        print f,

 

9-8:

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

moduleName = raw_input(u"输入模块名: ")
try:
    module = __import__(moduleName)
except:
    print u"输入的模块不存在"

moduList = dir(module)

print "%-20s%-20s%-20s" % ('module name', "type", "value")
for attr in moduList:
    moduType = type(getattr(module, attr))
    value = getattr(module, attr)
    print "%-20s%-20s%-20s" % (attr, moduType, str(value))

 

9-9:

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

import os

cwd = r'c:\Python27\Lib'
output1 = open('withDoc.txt', 'a+')
output2 = open('withoutDoc.txt', 'a+')

files = []
def fun(path):
    ls = os.listdir(path)

    for p in ls:
        p = os.path.join(path, p)
        if os.path.isdir(p):
            fun(p)
        else:
         files.append(p)

fun(cwd)

for file in files:
    f = open(file, 'r')
    isDoc = False
    doc = None

    for line in f:
        if (not isDoc) and line.count('"""') == 2:
            doc = line.split('"""')[-2]
            isDoc = False
        elif (not isDoc) and ('"""' in line):
            isDoc = True
            doc = line.split('"""')[-1]
        elif isDoc and ('"""' in line):
            doc += line.split('"""')[0]
            isDoc = False
        elif isDoc:
            doc += line
        elif not isDoc:
            if doc != None:
                break

    if doc != None:
        output1.write("文件名:" + file + "\n")
        output1.write("文件内容如下:" + "\n")
        output1.write(doc + "\n")
    else:
        output2.write('文件名:' + file + "\n")

    f.close()

output1.close()
output2.close()

 

9-13:

import sys

for arg in range(1, len(sys.argv)):
    print sys.argv[arg]

 

9-15:

import os

fsource = open('text1.txt', 'r')
ftarget = open('text2.txt', 'w')

for line in fsource:
    ftarget.write(line)

fsource.close()
ftarget.close()

 

9-19:

import random

c = raw_input('what\'s your input? ')
n = raw_input('times is: ')
l = raw_input('total length is: ')
chrVal = chr(int(c))
times = int(n)
length = int(l)

context = []
for n in range(length -times):
    randVal = random.randint(0, 255)
    randChr = chr(randVal)
    while randChr == chrVal:
        randVal = random.randint(0, 255)
        randChr = chr(randVal)
    context.append(randChr)

for n in range(times):
    contextlen = len(context)
    insertIndex = random.randrange(0, contextlen)
    context.insert(insertIndex, chrVal)

file = open('text2.txt', 'wb')
file.writelines(context)
file.close()

 

9-20:

import zipfile

zfile = zipfile.ZipFile ('hello.zip', 'w')
zfile.write("text1.txt")

 

9-21:

不会写,抄来的,稍稍改了下

import os
import zipfile

def zipdir(path, zip):
    for dirpath, dirnames, filenames in os.walk(path):
        for file in filenames:
            if file == zip.filename:
                continue
            zip.write(os.path.join(dirpath, file))

if __name__ == '__main__':
    zip = zipfile.ZipFile('Python.zip', 'w')
    print zip.filename
    cwd = os.getcwd()
    zipdir(cwd, zip)
    zip.close()

转载于:https://my.oschina.net/hounLeft/blog/687310

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值