zoukankan      html  css  js  c++  java
  • A Byte of Python 笔记(10)输入/输出:文件和储存器

    第12章  输入/输出

    大多数情况下,我们需要程序与用户交互。从用户得到输入,然后打印一些结果。

    可以分别使用 raw_input 和 print 语句来完成这些功能。对于输出,可以使用多种多样的 str(字符串)类。

    另一个常用的输入/输出类型是处理文件。创建、读和写文件的能力是许多程序所必须的。

    文件

    通过 file 类的对象来打开一个文件,使用 file 类的 read、readline 或 write 方法来恰当地读写文件。对文件的读写能力依赖于打开文件时指定的模式(模式可以为读模式('r')、写模式('w')或追加模式('a'))。最后完成对文件的操作时,调用 close 方法完成对文件的使用。

    # -*- coding: utf-8 -*-
    # Filename: using_file.py
    
    poem = '''
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
        use Python!
    '''
    
    f = file('poem.txt', 'w') # open for 'w'riting
    f.write(poem) # write text to file
    f.close() # close the file
    
    f = file('poem.txt')
    # if no mode is specified, 'r'ead mode is assumed by default
    
    while True:
        line = f.readline()
        if len(line) == 0: # zero length indicates EOF
            break
        print line, # notice comma to avoid automatic newline added by Python
    
    f.close()

    image

    首先,使用写模式打开文件,然后使用 file 类的 write 方法来写文件,最后用 close 关闭文件。

    接下来,再一次打开同一个文件来读文件。如果不指定模式,默认为读模式。readline 方法读取文件的每一行,返回包括行末换行符的一个完整行。当一个空的字符串被返回时,表示文件末已经到达。

    最后,使用 close 关闭这个文件。文件读到的内容已经以换行符结尾,所以在 print 语句上使用逗号消除自动换行。

    储存器

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

    另一个 cPickle,功能和 pickle 模块完全相同,用 C 语言编写,比 pickle 快1000倍。

    # -*- coding: utf-8 -*-
    # Filename: using_pickling.py
    
    import cPickle as p
    #import pickle as p
    
    shoplistfile = 'shoplist.data'
    # the name of the file where we will store the object
    
    shoplist = ['apple','mango','carrot']
    
    # write to the file
    f = file(shoplistfile, 'w')
    p.dump(shoplist, f) # dump the object to a file
    f.close()
    
    del shoplist # remove the shoplist
    
    # read back from the storage
    f = file(shoplistfile)
    storedlist = p.load(f)
    print storedlist

    image

    首先,使用 import..as 语法,以便于使用更短的模块名称。

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

    取储存 过程:使用 pickle 模块的 load 函数的返回来取回对象。

  • 相关阅读:
    转载: jQuery事件委托( bind() live() delegate()) [委托 和 绑定的故事]
    转载:CPU的位数和操作系统的位数
    javascript 过滤空格
    转载: js jquery 获取当前页面的url,获取frameset中指定的页面的url(有修改)
    转载:struts标签<s:date>的使用
    转载:s:if的用法
    解决cordova-plugin-actionsheet导致Android丑陋的问题
    ionic框架对Android返回键的处理
    解决魅族手机无法连接Mac调试
    谷歌开发者大会传达的8条关键信息
  • 原文地址:https://www.cnblogs.com/blueskylcc/p/5360303.html
Copyright © 2011-2022 走看看