您的位置:首页 > 编程语言 > Python开发

python 核心编程课后练习(chapter 3)

2013-08-02 09:58 489 查看
3-8

#3-13
"readtextFile.py---read and display text"
import os
ls = os.linesep

print """Enter your option:
(w)create a file
(r)read a file
(m)modify a file
(others)exit
"""

def WriteFile(str):
all = []
if os.path.exists(str):
print "ERROR: '%s' already exists" % fname
return

print "\nEnter lines ('.' by itself to quit).\n"
while True:
entry = raw_input('newline:')
if entry == '.':
break
else:
all.append(entry)

fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print "DONE!"

def ReadFile(str):
#fname = raw_input("Enter file name:")
print

if os.path.exists(str):
fobj = open(str, 'r')
for eachline in fobj:
print eachline.strip()
fobj.close()
else:
print "file not exists!!"

def ModifyFile(str):
all = []
if os.path.exists(str):
i = 1
fobj = open(str, 'r')
for eachline in fobj:
newline = eachline.strip()
print "line %d: %s" % (i,newline)
newline = raw_input("replace with:")
all.append(newline)
i+=1
fobj.close()

opt = raw_input("do you want to save your changes,\ny(yes) \nother(n):")
if opt == 'y':
output = open(str, 'w')
output.writelines(['%s%s' % (x, ls) for x in all])
output.close()
else:
return
else:
print "file not exists!!"

opt =raw_input("your option is:")

if(opt == 'w'):
fname = raw_input("the file to write is: ")
WriteFile(fname)
elif opt== 'r':
fname = raw_input("the file to read is: ")
ReadFile(fname)
elif opt == 'm':
fname = raw_input("the file to modify is:")
ModifyFile(fname)
print "the new file content is:"
ReadFile(fname)
else:
print "exit"


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: