zoukankan      html  css  js  c++  java
  • Python3基础16——file对象测试数据的读写与操作

    file txt xml html --->
    mode 打开这个文件的模式,主要有以下:

    'r'      open for reading (default)
    'w'     open for writing, truncating the file first
    'x'     create a new file and open it for writing
    'a'     open for writing, appending to the end of the file if it exists
    'b'    binary mode(二进制模式)
    't'    text mode (default)
    '+'     open a disk file for updating (reading and writing)
    'U'     universal newline mode (deprecated)

    r  w  a
    r+   w+   a+
    read  write  append
    rb rb+ wb wb+ ab ab+ 做单元测试的时候

    1:file文件open之后默认是r 只读模式 如果你要写入内容 报错:io.UnsupportedOperation: not writable
    2:r+ 可读可写 先写的话 从头开始覆盖写 读光标之后的内容 读写跟着光标走
    3:如果要写入中文 要注意编码格式encoding

    1 file=open("python11.txt","r+",encoding='utf-8')
    2 res=file.read()#进行完一次读取操作后 光标就到文末
    3 file.write('卡卡777')
    4 print(res)

    4:w 只写 硬要去读 就会报错io.UnsupportedOperation: not readable
    5:  w+ 可读可写 不管是w 还是w+ 如果文件存在 就直接清空 再重写,如果文件不存在 则新建一个文件 然后写

    1 file=open("python12.txt","w",encoding='utf-8')
    2 file.write("8889999")

    6:a 追加 a+ 推荐

    1 file=open("python12.txt","a",encoding='utf-8')
    2 file.write("***Python106666")

    如果文件存在 就直接追加写 写在后面 如果不存在 则新建一个文件进行结果写入

    1 file=open("python13.txt","a",encoding='utf-8')
    2 file.write("
    ***Python106666")

    重点掌握两种 r a

     1 file=open("python13.txt","r",encoding='utf-8')
     2 print(file.read()) #读取所有内容
     3 
     4 print(file.readline())#按行读取
     5 
     6 print(file.readlines())#读取多行 返回的是列表
     7 
     8 file_2=open("python12.txt","a",encoding='utf-8')
     9 print(file_2.write("20181011 file 操作")) # .write()打印出来的是一个int,表示写入的长度同时写入内容到文件
    10 
    11 file_2.writelines(["777
    ","8888"])
  • 相关阅读:
    基于XMPP的即时通信系统的建立 — XMPP IQ详解
    XMPPManager 解析
    Xcode 工程文件“.xcodeproj”文件夹解析
    Description &&debugDescription && runtime(debug模式下调试model)
    day04作业
    数字、字符串、列表、字典,jieba库,wordcloud词云
    if,for,异常,random模块,计算圆周率
    day03
    day02
    计算机基础
  • 原文地址:https://www.cnblogs.com/monica711/p/9804865.html
Copyright © 2011-2022 走看看