9–15. 复制文件. 提示输入两个文件名(或者使用命令行参数 ). 把第一个文件的内容复制
9–17. 文本处理. 创建一个原始的文本文件编辑器. 你的程序应该是菜单驱动的, 有如下
这些选项:
1) 创建文件(提示输入文件名和任意行的文本输入),
2) 显示文件(把文件的内容显示到屏幕),
3) 编辑文件(提示输入要修改的行, 然后让用户进行修改),
4) 保存文件, 以及
5) 退出
的次数.
到第二个文件中去.
#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