一个简单的python读写文件脚本,, #!/usr/b


    #!/usr/bin/env python      'makeFile.py -- create a file'      import os      ls = os.linesep      # get filename      while True:          fname = raw_input('Input an unused file name >')          if os.path.exists(fname):              print "ERROR: '%s' already exists" %fname          else:              break      # get file content lines      all = []      print "\nEnter lines (input '.' to quit).\n"      # loop until user terminates input      while True:          entry = raw_input('>')          if entry == '.':              break          else:              all.append(entry)      # write lines to file with proper line-ending      fobj = open(fname, 'w')      fobj.writelines(['%s%s' %(x, ls) for x in all])      fobj.close()      print 'DONE'      if __name__ == '__main__':          print 'innter module'  

上面的代码用来创建一个新文件并写入文本,第6行给os模块中的linesep起了给别名ls,这样做的好处一方面简化了长长的变量名,另一方面也是主要原因用于提高代码性能,因为访问这个变量时首先要检测os模块,然后再解析linesep,linesep是行结束符标志,linux下是'\r',windows下是'\r\n',用本地变量保存更好。第34行使用了__name__,这主要用于代码内测试,它的值是__main__,但python文件通常作为模块被其它文件import,这时__name__的值是这个模块名,就不会执行模块内的测试代码了。

    #!/usr/bin/env python      'readFile.py -- read and display file'      # get filename      fname = raw_input('Enter filename >')      print       # attempt to open file for reading      try:          fobj = open(fname, 'r')      except IOError, e:          print "***** file open error:", e      else:          # display contents to the screen          for eachLine in fobj:              print eachLine,          fobj.close()  

上面的代码用来读文件并显示其内容到屏幕上,使用了try-except-else异常处理机制。

评论关闭