1. 程式人生 > >python 核心程式設計第二版9章習題答案(自寫)

python 核心程式設計第二版9章習題答案(自寫)

test 9.1

fileload = 'C:/Users/Administrator/Desktop/test/test9.1.txt'
f = open(fileload,'r')
for eachline in f:
    for ps in eachline:
        if ps == '#':
            print("is pass:%s"%ps)
            break
        else:
            print(ps,end = '')
f.close()

test 9.2

import os
fileload = 'C:/Users/Administrator/Desktop/test'
list = os.listdir(fileload) print("*****************") for i in list: print(i) print("*****************") N = int(input("******N = how many line you want:")) F = input("which file you want:") fileload_ = fileload + '/'+ F f = open(fileload_,'r') for lines in f: print(lines,end = ' ') N=N-1
if N<=0: break f.close()

test 9.3

import os
fileload = 'C:/Users/Administrator/Desktop/test'
list = os.listdir(fileload)
print("*****************")
for i in list:
    print(i)
print("*****************")
F = input("which file you want:")
fileload_ = fileload + '/'+ F
count = 0
f = open(fileload_,'r'
) for lines in f: count+=1 print("this file lines is:%d"%count) f.close()

test 9.4

import os
file_load = '/home/zz/Desktop/test'
print("This directory file is:", os.listdir(file_load))
while True:
    file_name = input("Enter a file name OR Enter exit to quit:")
    load = file_load + '/' + file_name
    if file_name == 'exit':
        break
    f = open(load)
    count = 0
    for i in f:
        print(i, end='')
        count += 1
        if count > 25:
            break
    continue

test 9.5

pass

test 9.6

import os
file_load = '/home/zz/Desktop/test'
print("This directory file is:", os.listdir(file_load))

a = input("first file you want to compare:")
b = input("second file you want to compare:")

a_load = file_load+'/'+a
b_load = file_load+'/'+b

f_a =open(a_load)
a_lines= f_a.readlines()
f_a.close()
f_b =open(b_load)
b_lines= f_b.readlines()
f_a.close()

print(a_lines)
print(b_lines)
count_column=0
count_line= min(len(a_lines),len(b_lines))
for i in range(0,count_line):
    if a_lines[i] == b_lines[i]:
        print("%d line is simple,first is:%s second is:%s"%(i+1,a_lines[i],b_lines[i]),end='')
    else:
        for at in range(min(len(a_lines[i]),len(b_lines[i]))):
            if a_lines[i][at] != b_lines[i][at]:
                print("%d line %d column is different,first is:%s second is:%s" %(i+1,at+1,a_lines[i],b_lines[i]),end='')
                break

test 9.8

'''
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case'''
#getattr(object, name[, default]) -> value

mod = input("enter module name:")
module = __import__(mod)
m = dir(module)
for i in m:
    print("name :%s"%i)
    print(type(getattr(module,i)))
    print(getattr(module,i))