python核心编程第九章习题答案(3)

9–15.   复制文件. 提示输入两个文件名(或者使用命令行参数 ). 把第一个文件的内容复制

到第二个文件中去. 

#filename:test9-15.py

def copyfile():
    fs=raw_input("source file:").strip()
    #fd=raw_input("destination file:").strip()
    fd="G:\\copy.txt"

    fsp=open(fs,'r')
    fdp=open(fd,'w')

    for line in fsp:
        fdp.writelines(line)

    fsp.close()
    fdp.close()

copyfile()

9–17.   文本处理. 创建一个原始的文本文件编辑器. 你的程序应该是菜单驱动的, 有如下
这些选项: 
1) 创建文件(提示输入文件名和任意行的文本输入), 
2) 显示文件(把文件的内容显示到屏幕), 
3) 编辑文件(提示输入要修改的行, 然后让用户进行修改), 
4) 保存文件, 以及 
5) 退出

#filename:9-17.py

import os
ls=os.linesep
fname=''

def createfile():
    prompt="Enter file name:"
    while True:
        fname=raw_input(prompt).strip()
        if os.path.exists(fname):
            prompt="Already exist,Enter another:"
        else:
            break
    fp=open(fname,'a+')
    prompt="Input one line:"
    while True:
        eachline=raw_input(prompt)
        if eachline!='':
            fp.write('%s%s'%(eachline,ls))
            prompt="Input another line:"           
        else:
            break
    fp.close()

    
def showfile():
    fname=raw_input("Enter file name:").strip()
    fp=open(fname,'r')
    for line in fp:
        print line,
    fp.close()

    
def editfile():
    fname=raw_input("Enter file name:").strip()
    fp=open(fname,'r')
    old=fp.readlines()
    fp.close()
    while True:
        l  = raw_input("Enter line to edit:").strip()
        if l=='q':
            break
        line=int(l)
        lcontent=raw_input("Enter content:")
    
        if line > len(old):
            old.append(lcontent)
        else:
            old[line]=lcontent
    fp=open(fname,'a')
    fp.truncate()
    for cont in old:
        fp.write('%s%s'%(cont,ls))
    fp.close()
                  
    
def savefile():
    pass
def showmune():
    notice='''
    ----------------------------------------------
    1) 创建文件(提示输入文件名和任意行的文本输入), 
    2) 显示文件(把文件的内容显示到屏幕), 
    3) 编辑文件(提示输入要修改的行, 然后让用户进行修改), 
    4) 保存文件, 以及 
    5) 退出. 
    -----------------------------------------------
    >>'''
    while True:
        choice=int(raw_input(notice).strip())
        if choice==1:
            createfile();
        elif choice==2:
            showfile();
        elif choice==3:
            editfile();
        elif choice==4:
            savefile();
        else:
            break


if __name__=="__main__":
    showmune()
        
9–18.   搜索文件. 提示输入一个字节值(0 - 255)和一个文件名. 显示该字符在文件中出现
的次数.

#filename:test9-18.py

fn=raw_input("file:")
n=int(raw_input("num:").strip())
char=chr(n)

fp=open(fn,'r')
all_line=fp.readlines()
fp.close()

context=''.join(all_line)
cnt=context.count(char)
print cnt



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值