zoukankan      html  css  js  c++  java
  • python读写数据篇

    一.读写数据
    1.读数据
    #使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
    file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )
    #注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

     

    #读文本文件
    input = open('data', 'r')
    #第二个参数默认为r
    input = open('data')
    

      

    2.写数据
    file_object = open('content.txt', 'w')
    file_object.write(content)
    file_object.writelines(list_of_text_strings)  #写入多行
    file_object.close()
    注意,调用writelines写入多行在性能上会比使用write一次性写入要高。
    完整:https://www.cnblogs.com/allenblogs/archive/2010/09/13/1824842.html

    追加数据
    f = open('test.txt', 'a', encoding='utf8')
    f.write('
    ')
    f.write('abc')
    f.close()
    

      



  • 相关阅读:
    UVA756
    SP30906
    SP32900
    CF940F
    洛谷P5030
    洛谷P5142
    洛谷P2569
    网络流 24 题做题记录
    矩阵
    二分图
  • 原文地址:https://www.cnblogs.com/cxscode/p/8079525.html
Copyright © 2011-2022 走看看