Python核心编程第二版第三章Python基础(课后习题)----我的答案(续)

时间:2022-05-20 08:32:46
3-10.(b).
import os
ls = os.linesep  
while True:  
	fname = raw_input('enter a name')  
	if os.path.exists(fname):
		fobj = open(fname, 'r')
		for eachline in fobj:
			print eachline,
		fobj.close()
	else:
		print 'file open error'
		break
3-11.
fname = raw_input("Enter filename: ")
print fname
try:
    fobj = open(fname, "r")
except IOError, e:
    print "*** file open error:", e
else:
    for eachLine in fobj:
        print eachLine.strip('\n')
    fobj.close()
3-12.
# -*- coding: utf-8 -*-

import os

ls = os.linesep
chioce = raw_input('Choice read or make a new file:"r" or "m" : ')
while True:
	if chioce == 'm':
		fname = raw_input('Enter a name')
		try:
			fobj = open(fname, 'r')
		except IOError, e:
			print "file open error"
			break
		
		all = []
		print "\nEnter lines ('.' by itself to quit).\n"

		while True:
			entry = raw_input('Whatever you want to say: ')
			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'
	
	elif chioce == 'r':
		fname = raw_input("Enter filename: ")
		print fname
		try:
			fobj = open(fname, "r")
		except IOError, e:
			print "*** file open error:", e
		else:
			for eachLine in fobj:
				print eachLine.strip('\n')
		fobj.close()
	
	else:
		print 'exit'
		break
3-13.pass