核心编程答案(第三章)

3-10

#!/usr/bin/env python
# encoding: utf-8

import os
ls = os.linesep
fname = raw_input('Enter file name: ')

all = []

try:
    fobj = open(fname, 'r')
    print "'%s already exists'" % fname
except IOError, e:
    print "\nEnter lines ('.' by itself to quite). \n"
    while True:
        entry = raw_input('>')
        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!"

 

#!/usr/bin/env python
# encoding: utf-8
import os
'readTextFile.py -- read and display text file'

fname = raw_input('Enter filename: ')
print

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

 3-11 srtip()是将最两边全部匹配的给删除,参数为空时删除空白空间

#!/usr/bin/env python
# encoding: utf-8
import os
'readTextFile.py -- read and display text file'

fname = raw_input('Enter filename: ')
print

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

 3-12

#!/usr/bin/env python
# encoding: utf-8

import os
ls = os.linesep

choice = raw_input("What do you want to do? '1' mean write and '2' mean read: ")
if choice == '1':
    fname = raw_input('Enter file name: ')
    all = []
    try:
        fobj = open(fname, 'r')
        print "'%s already exists'" % fname
    except IOError, e:
        print "\nEnter lines ('.' by itself to quite). \n"
        while True:
            entry = raw_input('>')
            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 choice == '2':
    fname = raw_input('Enter filename: ')
    print

    if os.path.exists(fname):
        fobj = open(fname, 'r')
        for eachline in fobj:
            print eachline.strip('\n')
        fobj.close()
    else:
        print "file open Error! "
else:
    print "you don't put the right number!"

 

posted @ 2016-05-01 22:55  ohmydenzi  阅读(157)  评论(0编辑  收藏  举报