• 文件扩展相关


    一、文件权限扩展
      1. "r+"
        r+ 写入的位置是 当前光标所在位置,会直接改写当前位置的值
        r+ 可以续写么? 可以,但是必须把光标挪到最后
        r 没有创建文件的能力
    1  r_file = open("cc.txt", "r+", encoding="utf-8")
    2  r_file.write("666
    ")
    3  r_file.close()
    4 
    5  r_file1 = open("cc.txt", "r+", encoding="utf-8")
    6  print(r_file1.read())
    7  print(r_file1.tell())
    8  r_file1.write("333
    ")
    9 r_file1.close()

      2."w+"

        w+ 拥有写入权限,可以创建文件

        w 所有的write操作是先写在内存中,只有结束的时候才会执行进去

        w+ 和 r+ 的区别是 r+ 只在当前位置写入,w+ 是全部重写内容

     1 w_file1 = open("www.txt", "w+", encoding="utf-8")
     2 w_file1.write("aaa
    ")
     3 w_file1.close()
     4 
     5 w_file = open("www.txt", "w", encoding="utf-8")
     6 w_file.write("123
    ")
     7 w_file.write("123
    ")
     8 w_file.write("123
    ")
     9 w_file.write("123
    ")
    10 w_file.write("123
    ")
    11 w_file.close()

      3"a+"

       a 是追加 a+ 追加

    1 a_file = open("a.txt","a",encoding="utf-8")
    2 a_file.write("555
    ")
    3 a_file.close()
    4 
    5 a_file1 = open("a.txt", "a+", encoding="utf-8")
    6 a_file1.write("333
    ")
    7 a_file1.close()

    二、with 

    自动管理上下文
    数据库连接
    多线程
     1 #   写文件的函数 filename,content
     2 def write_file(filename:str,content:str,type:int=1):
     3     with open(filename,'w') as fw:
     4         fw.write(content)
     5 
     6 def read_file(filename):
     7     with open(filename,) as fw:
     8         return fw.read()
     9 #  调用函数写入文件、读取文件
    10 write_file("a.txt","cheng成",2)
    11 
    12 print(read_file("a.txt"))
  • 相关阅读:
    JS DOM2级事件兼容处理
    JS DOM2级事件基础
    JS 事件基础
    JS 动态规划 LeetCode 一和零
    JS 动态规划入门
    JS 动画优化 代码篇
    LeetCode笔记整理1 摩尔投票法
    LeetCode笔记整理3 二叉树中序遍历 Morris中序遍历
    java面向对象编程——第四章 类和对象
    java面向对象编程——第六章 数组
  • 原文地址:https://www.cnblogs.com/huajie-chj/p/14265389.html
Copyright © 2020-2023  润新知