zoukankan      html  css  js  c++  java
  • python 文件操作

    文件操作

    1.r(只读模式)

    2.w(只写模式)

    3.a(追加模式)

    以上为纯净模式

    1.r+

    # with open(r'test',mode='r+',encoding='utf-8') as f:
    #     print(f.readable())
    #     print(f.writable())
    #     print(f.readline())
    #     f.write('嘿嘿嘿')

    2.w+

    # with open(r'test',mode='w+',encoding='utf-8') as f:
    #     print(f.readable())
    #     print(f.writable())
        # print(f.readline())
        # f.write('嘿嘿嘿')

    3.a+

    4.r+b

    with open(r'tst',mode='r+b') as f:
        print(f.readable())
        print(f.writable())
        res = f.read()
        # print(res.decode('utf-8'))
        res1 = str(res,encoding='utf-8')
        print(res1)

    文件光标的移动

    1.在rt模式下,read内的数字表示的是字符的个数

    文件内光标的移动

    '''
    f.seek(offset,whence)
    offst:相对偏移量  光标移动的位数
    whence:
        0.参照文件的开头   t和b都可以使用
        1.参照光标所在的当前位置  只能在b模式下用
        2.参照文件的末尾  只能在b模式下用
    '''
    with open(r'tst','r',encoding='utf-8') as f:
        print(f.read(1))
        f.seek(6.0)   #seek移动都是字节数
        f.seek(4,0)    #seek移动都是字节数
    with open(r'tst','rb',encoding='utf-8') as f:
        print(f.read(3).decode('utf-8'))
        f.seek(0,0)
        print(f.read(1).decode('utf-8')
        f.seek(6,0)   #移动的都是字节数
        
    with open (r'tst','rb') as f:
         print(f.read())
         f.seek(-4,2)
         print(f.read().decode('utf-8'))
    with open (r'tst','r+','utf-8') as f:
        f.seek(3,0)
        f.write('')

    写日志

    import  time
    res = time.strftime('%Y-%m-%d %X')
    print(res,type(res))
    with open(r'tst','a',encoding='utf-8') as f:
        f.write('%s egon给jason发了一块钱'%res)

    检测内容

    with open(r'tst','rb') as f:
        f.seek(0,2)
        while True:
        res = f.readline() #查看光标移动了多少位  bytes    
        print(f.tell())
        if res:
            print('新增的文件的文件内容:%s'%res.decode('utf-8'))
            #说明有人操作当前文件
            else#说明文件没有被操作
              print('暂时未被操作')

    截断文件

    with open (r'tst','a',encoding='utf-8') as f:
        f.truncate(6)  #接收的字节的长度 整型
        #保留0~6字节  后面的全被删除(截断)
  • 相关阅读:
    小程序开发-7-访问api数据与ES6在小程序中的应用
    小程序开发-8-流行页面编码与组件的细节知识
    小程序开发-6-组件数据、事件与属性
    当安装mongodb客户端出现了Failed to load list of databases
    对bluebird的理解
    百度地图实现案例
    iScroll实现下拉刷新上拉加载
    nodejs环境变量配置
    检测Python程序本身是否已经在运行
    用Python快速找到出现次数最多的数据
  • 原文地址:https://www.cnblogs.com/KrisYzy/p/11151334.html
Copyright © 2011-2022 走看看