Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1342303
  • 博文数量: 243
  • 博客积分: 888
  • 博客等级: 准尉
  • 技术积分: 2955
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-05 14:33
个人简介

漫漫长路,其修远兮!

文章分类

全部博文(243)

文章存档

2017年(2)

2016年(22)

2015年(32)

2014年(57)

2013年(107)

2012年(23)

分类: Python/Ruby

2014-04-01 21:37:56


点击(此处)折叠或打开

  1. import os
  2. ls=os.linesep

  3. numlist=['1','2','3']
  4. def getnum():
  5.     num=raw_input('''
  6.     |------------|
  7.     | 1.red |
  8.     | 2.write|
  9.     | 3.quit |
  10.     |------------|
  11.     Please enter your select num:\n''')
  12.     if num in numlist:
  13.        return num
  14.     else:
  15.        return getnum()

  16. def getfile():
  17.     file=raw_input('enter filename:')
  18.     if file=="":
  19.        return getfile()
  20.     else:
  21.        return file

  22. def getcomment():
  23.     print 'enter comment or quit to exit'
  24.     lines=[]
  25.     while True:
  26.           line=raw_input('>')
  27.           if line=='quit':
  28.              return lines
  29.           else:
  30.              lines.append(line)

  31. def read():
  32.     if os.path.exists(file):
  33.        f=open(file,'r')
  34.        for line in f:
  35.            print line
  36.        f.close()
  37.     else:
  38.        print 'Error:%s not exists' % file
  39.     return getfile()

  40. def write():
  41.     if os.path.exists(file):
  42.        f=open(file,'a')
  43.        f.writelines(['%s%s'%(x,ls) for x in com])
  44.        f.close()
  45.        print 'append'
  46.     else:
  47.        f=open(file,'w')
  48.        f.writelines(['%s%s'%(x,ls) for x in com])
  49.        f.close()
  50.        print 'write to new file'

  51. while True:
  52.     num=getnum()
  53.     if num=='1':
  54.        file=getfile()
  55.        read()
  56.     elif num=='2':
  57.        file=getfile()
  58.        com=getcomment()
  59.        print com
  60.        write()
  61.     else:
  62.        print 'exit'
  63.        break

关于其他文件操作方式
http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html
http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html

阅读(1062) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~