python核心编程第三章练习题12

#python核心编程第三章练习题12
 
 
import os
def makeTextFile():
	while True:
		linesep=os.linesep
		fname = raw_input("type the file name to write\n(move back by 'q'): ")
		if fname.strip().lower() == 'q':
			break
		try:
			fobj = open(fname,'r')
		except IOError, e:
			allf = []
			print "\nenter lines to write ('.' by itself to quit)"
			while True:
				entry = raw_input('>>').rstrip()
				if entry == '.':
					break
				else:
					allf.append(entry)
			fobj  = open(fname,'w')
			fobj.writelines(['%s%s' % (x,linesep) for x in allf])
			fobj.close()
			print 'DONE'
			break
		else:
			print "Error :file '%s' already exists " % fname
			fobj.close()
def readTextFile():
	while True:
		fname = raw_input("Enter a filename to read \n(move back by 'q'): ")
		if fname.strip().lower()  == 'q':
			break
		try:
			fobj = open(fname,'r')
		except IOError, e:
			print "Error occurs: no such filename as: '%s',try again! " % fname
		else:
			fobj = open(fname,'r')
			for eachline in fobj:
				print eachline.rstrip()
			fobj.close()
			break

def choseMode():
	while True:
		try:
			mode = eval(raw_input('\nplease chose the mode to read \nor make a file \n(True=make,False=read):').strip())
		except SyntaxError:
			mode = False
		if mode:
			makeTextFile()
		else:
			readTextFile()
if __name__ == '__main__':
	choseMode()


你可能感兴趣的:(编程,python,练习)