zoukankan      html  css  js  c++  java
  • ⅩⅡ:操作文件的方法

    一:读相关操作

    1、readline:一次读一行

    with open(r'g.txt',mode='rt',encoding='utf-8') as f:
        res1=f.readline()
        res2=f.readline()
        print(res2)
    
        while True:
            line=f.readline()
            if len(line) == 0:
                break
            print(line)
    

    2、readlines:

    with open(r'g.txt',mode='rt',encoding='utf-8') as f:
        res=f.readlines()
        print(res)
    

    强调:

    • f.read()与f.readlines()都是将内容一次性读入内存,如果内容过大会导致内存溢出,若还想将内容全读入内存,

    二:写相关操作

    # 1.f.writelines():
    
    with open('h.txt',mode='wt',encoding='utf-8') as f:
        f.write('1111
    222
    3333
    ')
    
        l=['11111
    ','2222','3333',4444]
        l=['11111
    ','2222','3333']
        for line in l:
            f.write(line)
        f.writelines(l)
    
    with open('h.txt', mode='wb') as f:
        l = [
            '1111aaa1
    '.encode('utf-8'),
            '222bb2'.encode('utf-8'),
            '33eee33'.encode('utf-8')
        ]
    
        # 补充1:如果是纯英文字符,可以直接加前缀b得到bytes类型
        l = [
            b'1111aaa1
    ',
            b'222bb2',
            b'33eee33'
        ]
    
        # 补充2:'上'.encode('utf-8') 等同于bytes('上',encoding='utf-8')
        l = [
            bytes('上啊',encoding='utf-8'),
            bytes('冲呀',encoding='utf-8'),
            bytes('小垃圾们',encoding='utf-8'),
        ]
        f.writelines(l)
    
    # 3、flush:
    with open('h.txt', mode='wt',encoding='utf-8') as f:
        f.write('哈')
        # f.flush()
    
    # 4、了解
    with open('h.txt', mode='wt',encoding='utf-8') as f:
        print(f.readable())
        print(f.writable())
        print(f.encoding)
        print(f.name)
    
    print(f.closed)
    
  • 相关阅读:
    努力 加油
    大总结(全文手打)加深记忆 表单 注册页面的第一次制作 小白一只多多包含
    购物栏
    三级轮播
    图片轮播
    啊!!苦等,博客终于通过了!!
    SQL升级Oracle挖的Null坑,你懂的!
    关于master..xp_cmdshell’的几个错误_解决办法(转)
    班级博客
    图片系统架构思考之一:删除图片--不容忽视
  • 原文地址:https://www.cnblogs.com/qujiu/p/12504218.html
Copyright © 2011-2022 走看看