zoukankan      html  css  js  c++  java
  • 文件的输入输出

    文件的输入输出:
    fileobj=open(filename,mode)
    Moded的第一个子母表示对其的操作:
    r 读模式
    w 写模式,如果文件不存在的话,则创建,如果存在则重新写新内容
    X 如果文件不存在的情况下,新创建并写文件
    a 如果文件存在,则在末尾添加内容
    Mode的第二个字母表示的是文件的类型
    t 代表文本类型
    b 代表二进制文件

    使用write()写文本文件

    >>> poem=''' there was a young lady named bright,
    ... whose speed was far faster than light
    ... in a relatived way
    ... '''
    >>> len(poem)
    95
    >>> fout=open('relativity','w')
    >>> fout.write(poem)
    >>> 
    >>> fout.close()
    

    使用read(),readline(),或者readlines()读文本文件
    读取文件的最简单的方式就是使用一个迭代器,它会每次返回一行,

    >>> poem=''
    >>> fin=open('relativity','r')
    >>> for line in fin:    
    ...     poem+=line
    ... 
    >>> fin.close()
    >>> len(poem)
    95
    

    函数readlines()调用时每次读取一行,并返回单行字符串列表‘

    >>> fin=open('relativity','r')
    >>> lines=fin.readlines()
    >>> fin.close()
    >>> for line in  lines:
    ...     print line
    ... 
     there was a young lady named bright,
    
    whose speed was far faster than light
    
    in a relatived way
    

    使用write()写二进制文件

    >>> bdata=bytes(range(0,256))
    >>> len(bdata)
    1170
    >>> fout=open('bfile','wb')
    >>> fout.write(bdata)
    >>> fout.close()
    

    使用with自动关闭文件
    Python的上下文管理器会清理一些资源,例如打开的文件,它的形式为with expression as variable

    >>> poem='aaa bbb ccc ddd'
    >>> with open('relativity','wt') as fout:
    ...     fout.write(poem)
    ... 
    
    

    完成上下文管理器的代码后,文件会自动关闭。

    使用seek()改变位置

    Python都会跟踪文件的位置,函数tell()返回距离文件开始处的字节偏移量,函数seek()允许跳转到文件其他字节偏移量的位置,
    >>> fin=open('bfile','rb')
    >>> fin.tell()
    0
    >>> fin.seek(255)
    >>> bdata=fin.read()
    >>> len(bdata)
    916
    >>> bdata[0]
    '6'
    

    Seek()同样返回当前的偏移量
    用第二个参数调用函数seek(): seek(offset:origin)
    如果origin等于0,默认为0,从开头偏移offset个字节
    如果origin等于1,从当前位置偏移offset个字节
    如果origin等于2,距离最后结尾处偏移offset个字节

  • 相关阅读:
    低调 、隐忍、善良应是最应该修炼的
    达内C++培训课程
    这三天低效率开发的总结,我都做了些什么啊?
    linux sysfs(1)
    编码问题
    Linux中的system函数的实现和解释
    北京邮电大学 程序设计课程设计 电梯 文件输入版本(已调试,大致正确运行==)
    "Dallas" CTP3 发布通告
    结合使用PowerPivot 和 "Dallas" CTP3
    Windows Azure 解决方案系列: 能源监测减少支出,通过托管平台拓展业务
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5704371.html
Copyright © 2011-2022 走看看