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


    文件操作

    hello = bytes('hello',encoding='utf-8')
    print(hello)
    # 二进制 python解释器 程序员

    bytes 转换为 字符串有一下两种方法,str(),decode()
    hello1 =str(hello,encoding='utf-8')
    hello2 = hello.decode('utf-8')


    r ,只读模式【默认】
    w,只写模式【不可读;不存在则创建;存在则清空内容;】
    x, 只写模式【不可读;不存在则创建,存在则报错】
    a, 追加模式【可读; 不存在则创建;存在则只追加内容;】

    # 以wb的方式打开,避免忘记关闭用with as

    with open('a.txt','wb') as f:
    str = '乔丹'
    byt_str = bytes(str,encoding='utf-8')
    f.write(byt_str)




    f.tell() 读取指针位置
    f.seek() 设置指针位置
    f.read() 不添加参数,默认读取全部
    f.readline() 读取一行数据
    f.truncate() 截取指针以前的数据
    f.close()
    f.flush()
    f.write()

    r+ 从头开始读,写追加,指针移到最后
    f = open('a.txt','r+',encoding='utf-8')
    print(f.tell())
    print(f.read(3)) # 默认是以字符方式读取,如果是rb+则是字节方式读取,一个汉字3个字节
    print(f.tell())

    print(f.read(3)) # 在close之前,下一次读取记住上一次读取的位置
    print(f.tell())

    f.seek(0)
    print(f.read(3))
    print(f.tell())

    f.write('sb') # 写的时候最后,把指针跳到最后在写
    print(f.tell())
    f.close()

    3.w+ 先清空,再写指针到最后,设置指针位置再读

    f = open('a.txt','w+',encoding='utf-8')
    print(f.read())

    f.write('乔丹')
    f.seek(0)
    print(f.read())

    f.close()

    x+ 和w+相同,如果文件纯在报错

    a+ 因为a为追加,所有打开的同时,指针已经到最后了,
    f = open('a.txt','a+',encoding='utf-8')
    print(f.tell())
    f.write('sb')
    f.seek(0)
    print(f.read())
    f.close()


    f = open('a.txt','r+')
    print(f.tell())
    print(f.seek(20))
    f.truncate()
    f.close()

    f = open('a.txt','r') # f 对象被循环
    for i in f:
    print(i,end='')

    自动close,with 同时打开两个文件,
    with open('a.txt','r') as f1, open('c.txt','w')as f2:
    for eachline in f1:
    f2.write(eachline)


  • 相关阅读:
    如何删除PeopleSoft Process Definition
    你真的了解PeopleSoft中的function和method方法嘛
    PeopleCode事件和方法只用于online界面不能用于组件接口(component interface)
    Lucene.Net 3.0.3如何从TokenStream中获取token对象
    从零开始搭建一个简单的基于webpack的vue开发环境
    Vue路由懒加载
    减少打包组件vue.config.js——Webpack的externals的使用
    axios全局配置及拦截器
    vue-cli中eslint配置
    DDD领域驱动设计基本理论知识总结
  • 原文地址:https://www.cnblogs.com/lovuever/p/6639613.html
Copyright © 2011-2022 走看看