1.文件写入
#coding:utf-8#!/usr/bin/env python'makeTextPyhton.py -- create text file'import osls = os.linesep#输入文件名fname = raw_input('Enter file name:')# 判断输入的文件名是否存在while True: if os.path.exists(fname): print "错误:'%s' 已经存在" % fname else: break#按行输入文件的内容,以.为结束每一行,以单个.结束整个输入all = []print "\n请以.结束每一行内容\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 "完成!"
2.文件读取和显示
#coding:utf-8#!/usr/bin/env python'readTextPyhton.py -- read and display text file'#输入文件名fname = raw_input('Enter file name:')print#尝试打开和显示文件try: fobj = open(fname,'r')except IOError,e: print "*** file open error:",eelse: #显示内容 for eachLine in fobj: print eachLine, fobj.close()