• python之路--day7


    字符编码

    # x='你好'
    # res=x.encode('utf-8')  encode编码---unicode转成其他编码
    # print(res,type(res))
    #
    # print(res.decode('gbk'))  decode -----其他编码解码成unicode
    

    文件打开模式之b模式

    b---字节(bytes)

    强调:

    1,与t模式类似不能单独使用,必须是rb,wb,ab

    2,b模式下读写都是以bytes为单位的

    3,b模式下一定不能指定encoding参数

    rb模式

    # with open('1.jpg',mode='rb',) as f:
    #     data=f.read()
    #     print(data,)
    #     print(type(data))
    
    # with open('db.txt',mode='rb',) as f:
    #     data=f.read() #
    #     print(data.decode('utf-8')) #bytes-----unicode
    #     print(type(data))

    wb模式

    # with open('b.txt',mode='rb') as f:
    #     data=f.read()
    #     print(data.decode('utf-8'))
    # with open('1.jpg',mode='rb') as f:
    #     data=f.read()
    #     print(type(data))
    #     print(data.decode('utf-8'))

    ab模式

    # with open('b.txt',mode='ab') as f:
    #     f.write('你好'.encode('utf-8'))

    文件打开模式补充

    可读可写

    #r+t
    with open('b.txt','r+t',encoding='utf-8') as f:
        # print(f.readable())
        # print(f.writable())
        print(f.readline())

    "+" 表示可以同时读写某个文件
    r+, 读写【可读,可写】
    w+,写读【可读,可写】
    a+, 写读【可读,可写】
    

    文件的修改

    f.seek()

    字节表示几个字符,由文件的字符编码决定

    # with open('user.txt','r+',encoding='utf-8') as f:
    #     f.seek(9) #偏移量的单位是字节

    #修改文件方式一:
    #1、先把文件内容全部读入内存
    #2、然后在内存中完成修改
    #3、再把修改后的结果覆盖写入原文件
    #缺点:会在文件内容过大的情况下,占用过多的内存

    # with open('user.txt',mode='r',encoding='utf-8') as f:
    #     data=f.read()
    #     data=data.replace('wxx','alex')
    #
    # with open('user.txt',mode='w',encoding='utf-8') as f:
    #     f.write(data)

    #修改文件方式二:
    #1、以读的方式打开原文件,以写的方式打开一个新文件

    import os
    
    with open('user.txt',mode='rt',encoding='utf-8') as read_f,
            open('user.txt.swap',mode='wt',encoding='utf-8') as write_f:
    
        for line in read_f:
            if 'wxx' in line:
                line=line.replace('wxx','alex')
    
            write_f.write(line)
    
    os.remove('user.txt')
    os.rename('user.txt.swap','user.txt')

    循环读取文件的内容:

        f = open('a.txt')
        for i in f():
            print(i,end='')
  • 相关阅读:
    NanUI文档
    NanUI文档
    NanUI文档
    开源组件NanUI一周年
    NanUI文档
    NanUI 0.4.4发布
    【开源】做了一个WinForm窗体的投影组件,能够为窗口添加影子效果
    NanUI for Winform 使用示例【第二集】——做一个所见即所得的Markdown编辑器
    NanUI for Winform 使用示例【第一集】——山寨个代码编辑器
    非常简洁简单的tcp socket库 XKSocket
  • 原文地址:https://www.cnblogs.com/guodengjian/p/8631218.html
Copyright © 2020-2023  润新知