zoukankan      html  css  js  c++  java
  • Python学习笔记_Chapter 4数据保存到文件

    1. What For

    将基于内存的数据存储到磁盘上,达到持续存储。

    2. HOW

    方法一: 将数据写到文件中


     常规的处理方式

    1 #file.x被打开的文件,model打开文件的方式
    2 out=open('file.x','model')
    3 #print将item写入到file指示的文件中,item可以是字符串或列表等
    4 print(item,file=out)
    5 #close是必须的,起到刷新输出的作用
    6 out.close()

    open('file','model')中model说明:

    文件存在:

    model= w 表示打开文件是为了写操作,这种写操作会先擦除文件现有内容。

    model= a 添加内容到文件内容尾部。

    model= w+ 读和写(不清楚)。

    文件不存在:

    自动创建新文件。

    用with处理文件

    作用:不必在担心文件的关闭,解释器为你处理。

    1 try:
    2     with open('file.x','w') as data:
    3           print(list,file=data)
    4 except IOError as err:
    5     print('FIle error'+str(err))

    方法二:腌制文件


     

    优点:通用的I/O,以何种格式写入文件就能以同样的格式取出来。

    Let's pickle:

    1 import pickle
    2 # write to pickle
    3 with open('file.pickle','wb') as data:
    4        pickle.dump([1,3],data)
    5 #read from pickle
    6 with open('file.pickle','rb') as data:
    7        list=pickle.load(data)

    注意:pickle处理文件的方式是二进制,pickle文件要以二进制打开‘wb’

    3. BULLET POINT

    a.不可变数据类型

    b.strip()方法: 去除字符串中的空格符

    c.try:

      except:

      finally:

    d.'a'+'b'  利用+连接两个字符

      str()  访问数据的串表示

    try:
    except IOError as err:
         print('File ERROR'+str(err))

    e. locals() -返回当前作用域中的变量集合,in 操作符检查成员关系

    1 try:
    2     data=open('file.txt','w')
    3 except:
    4 
    5 finally:
    6     if 'data' in locals():

    f. sys.stdout 标准输出

    print('',file=sys.stdout)

  • 相关阅读:
    TensorFlow学习笔记--CIFAR-10 图像识别
    第二章--第二节:注释
    webbrowser
    RichViewEdit
    RichEdit
    TreeView
    RichView
    ListView
    DesktopLoader服务程序
    Delphi实现程序只运行一次并激活已打开的程序
  • 原文地址:https://www.cnblogs.com/helo-blog/p/3853543.html
Copyright © 2011-2022 走看看