Differences between revisions 1 and 2
Revision 1 as of 2005-02-06 15:50:41
Size: 1217
Editor: ZoomQuiet
Comment:
Revision 2 as of 2009-12-25 07:10:09
Size: 1217
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 38: Line 38:
-- ZoomQuiet [[[DateTime(2005-02-06T15:50:41Z)]]] -- ZoomQuiet [<<DateTime(2005-02-06T15:50:41Z)>>]

创建内存文件

  • 你遇到的很多模块中的函式都需要一个文件对象作参数,有时候创建一个真的文件很麻烦,那未,感谢 Python吧,你可以通过"StringIO"模块来创建一个保存在内存中的文件来使用:
       1     import StringIO
       2 
       3     fileHandle = StringIO.StringIO ( "Let freedom ring." )
       4 
       5     print fileHandle.read() # "Let freedom ring."
       6 
       7     fileHandle.close() 
    
    • 还有 "cStringIO" 模块.与"StringIO" 一样的使用,如同"cPickle" 对"Pickle",这是更快的 C 语言现实:

         1     import cStringIO
         2 
         3     fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )
         4 
         5     print fileHandle.read() # "To Kill a Mockingbid"
         6 
         7     fileHandle.close() 
      


总结 Conclusion

  • 文件处理是很多语言应用时要经常面对的事务
  • 谢天谢地,Python 让这项任务变得的比其它语言要轻松的多
    • 提供了很多标准模块来帮助程序员
    • 而且面向对象的处置方式也令事情更加简单
  • 现在我们理解了Python 中基本的文件处理,那未轻松在你的应用中吧.


-- ZoomQuiet [2005-02-06 15:50:41]

FileManagementInPython/CreatingInMemory (last edited 2009-12-25 07:10:09 by localhost)