zoukankan      html  css  js  c++  java
  • 文件处理的r,w,a模式

      文件处理的r,w,a模式。

      一、基本概念

        打开文件的模式有三种纯净模式:r(默认的)w a

        控制操作文件内容格式的两种模式:t(默认的) b

        大前提:tb模式均不能单独使用,必须与纯净模式结合使用

        t文本模式:

          1、读写文件都是以字符串为单位的

          2、只能针对文本文件

          3、必须指定encoding参数

        b二进制模式:

          1、读写文件都是以Bytes/二进制为单位的

          2、可以针对所有文件

          3、一定不能指定encoding参数

      二、打开文件模式详解

          1、r只读模式:在文件不存在是则报错,文件存在文件内指针直接跳到文件开头

            with open(r('a.txt'),mode='rt',encoding='utf-8') as f:

              print(f.readlines())

          2、w只写模式:在文件不存在时会创建空文档,文件存在会清空文件,文件指针跑到文件开头

            with open(r'a.txt',mode='wt',encoding='utf-8') as f:

              print(f.readable())

              print(f.writeable())

              f.write('你好')

              f.write('wocale')

              lines = ['1111','22222','333333']

              f.writelines(lines)

          3、a只追加模式:在文件不存在时会创建空文档,文件存在会将文件指针直接移动到文件末尾

            with open(r'c.txt',mode='at',encoding='utf-8') as f:

              f.write('你好啊')

          b:读写都是以二进制为单位

            with open(r'b.txt',mode='rb') as f:

              data = f.read()

              print(data.encode('utf-8'))

            

            with open(r'1.png',mode='rb') as f:

              data = f.read()

              print(data.encode('utf-8'))

            

            with open(r'd.txt',mode='wb') as f:

              f.write('你好啊'.encode('utf-8'))

  • 相关阅读:
    ASM ClassReader failed to parse class file
    idea运行java项目js中文乱码如何解决
    Error:(182, 32) java: 常量字符串过长
    ssh启动报错:org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
    [Intro to Deep Learning with PyTorch -- L2 -- N14] Sigmoid function
    [CSS3] CSS Selector
    [HTML5] document.activeElement
    [Intro to Deep Learning with PyTorch -- L2 -- N9] Perceptron Trick
    [Javascript] Broadcaster, operator, listener pattern: Write a debounce operator -- 1
    [CSS] place-content = align-items + justify-content
  • 原文地址:https://www.cnblogs.com/xiaocaiyang/p/9681207.html
Copyright © 2011-2022 走看看