PythonTip >> 博文 >> python

python学习-读写文件

zihua 2014-01-16 18:01:55 点击: 738 | 收藏


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

import os

#os.linesep代表一个换行符
#window下是'\r\n',unix下是'\n'
ls = os.linesep

def readFile():
    fname = raw_input('Enter a filename: ')

    print

    try:
        fobj = open(fname,'r')
    except IOError, e:
        print '*** file open error:',e
    else:
        for eachLine in fobj:
            #print eachLine.rstrip('\n')
            #rstrip('\n')可以把字符串右侧所有的'\n'删除
            #print eachLine.lstrip('x')#可以把字符串左侧所有的字符x删除
            #strip('\n ')可以把字符串两端所有的'\n'和空格删除
            print eachLine,
        fobj.close()


def writeFile():

    while True:
        #<python核心编程>52页好像少写了下面这一行代码
        #这本书第一个demo就这么大个疏漏,实在不应该
        fname = raw_input('Enter a filename: ')
        if os.path.exists(fname):
            print 'error: %s already exists' % fname
        else:
            break


    all = []
    print '\nEnter lines (. by itself to quit).\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 'DOWN!'


if __name__ == '__main__':
    while True:
        want = raw_input('what you want?\n\'w\':write,\'r\':read :')
        if want == 'w':
            writeFile()
            break
        elif want == 'r':
            readFile()
            break
        else:
            continue

原文链接:http://my.oschina.net/mashiguang/blog/36788

作者:zihua | 分类: python | 标签: python | 阅读: 738 | 发布于: 2014-01-16 18时 |