zoukankan      html  css  js  c++  java
  • python 输入输出

    先看一个例子

    #coding:utf-8
    #Filename:using_flie.py
    '''
    Created on 2012-2-27
    @author: goodspeedcheng
    '''
    poem = '''\
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
            use Python!
    '''
    
    f = open('poem.txt','w',encoding='utf-8')
    f.write(poem)
    f.close()
    
    r = open('poem.txt')
    while True:
        line = r.read()
    	#line = r.readline()
    	#line = r.readlines()
        if len(line) == 0:
            break
        print(line)
    r.close() 

    >>>line = r.read()

    输出结果为

    Programming is fun
    When the work is done
    if you wanna make your work also fun:
            use Python!

    >>>line = r.readline()     

    输出结果为

    Programming is fun

    When the work is done

    if you wanna make your work also fun:

            use Python!

    >>>line = r.readlins()

    输出结果为

    ['Programming is fun\n', 'When the work is done\n', 'if you wanna make your work also fun:\n', '        use Python!\n']

    储存器

    Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

    什么东西能用pickle模块存储?

    • 所有Python支持的 原生类型 : 布尔, 整数, 浮点数, 复数, 字符串, bytes(字节串)对象, 字节数组, 以及 None.
    • 由任何原生类型组成的列表,元组,字典和集合。
    • 由任何原生类型组成的列表,元组,字典和集合组成的列表,元组,字典和集合(可以一直嵌套下去,直至Python支持的最大递归层数).
    • 函数,类,和类的实例(带警告)。
    #coding:utf-8
    #Filename:pickling.py
    '''
    Created on 2012-2-27
    @author: goodspeedcheng
    '''
    import pickle as p
    
    shoplistfile = 'shoplist.data'
    # the name of the file where we will store the object
    
    shoplist = ['apple','mango','carrot']
    
    #f = open(shoplistfile,'wb')
    #p.dump(shoplist,f)
    with open(shoplistfile,'wb') as f:
        p.dump(shoplist,f)
    f.close()
    
    del shoplist
    f = open(shoplistfile,'rb')
    storedlist = p.load(f)
    print(storedlist)

    执行代码将会输出:

    ['apple','mango','carrot']

    再次执行 只需执行

    f = open(shoplistfile,'rb')
    storedlist = p.load(f)
    print(storedlist)

    会输出同样的结果

    最新版本的pickle协议是二进制格式的。请确认使用二进制模式来打开你的pickle文件,否则当你写入的时候数据会被损坏。

    为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存

  • 相关阅读:
    图像的卷积
    信息理论与编码中有关信源编码的笔记
    Java 数组排序
    完全平方数
    Java 作业题4
    Java 作业题3
    Java 作业题 2
    算法面试题二:旋转数组,存在重复元素,只出现一次的数字
    算法面试题一:排序算法及贪心算法
    微信小程序 发送模板消息的功能实现
  • 原文地址:https://www.cnblogs.com/cacique/p/2370259.html
Copyright © 2011-2022 走看看