python 读写文件程序

主要最近学习python,两个练习的小例子,也是看书上写的,非常简单,感觉有点用

**********写文件**********

#_*_ coding:UTF-8 _*_

import os

ls = os.linesep

while True:

    fname = raw_input('输入文件名:')

    if os.path.exists(fname):

       print "ERROR:'%s' already exists" % fname

    else:

        break

all = []

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!'

**********读文件*********


#_*_ coding:UTF-8 _*_

import os


fname = raw_input('enter name')

print

try:

  fobj = open(fname,'r')

except IOERrror,e:

  print "file open error:",e

else:

  for earchLine in fobj:

      print earchLine

  fobj.close()


你可能感兴趣的:(python,读写文件)