咫尺天涯$

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
一、文件权限扩展
  1. "r+"
    r+ 写入的位置是 当前光标所在位置,会直接改写当前位置的值
    r+ 可以续写么? 可以,但是必须把光标挪到最后
    r 没有创建文件的能力
1  r_file = open("cc.txt", "r+", encoding="utf-8")
2  r_file.write("666\n")
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\n")
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\n")
 3 w_file1.close()
 4 
 5 w_file = open("www.txt", "w", encoding="utf-8")
 6 w_file.write("123\n")
 7 w_file.write("123\n")
 8 w_file.write("123\n")
 9 w_file.write("123\n")
10 w_file.write("123\n")
11 w_file.close()

  3"a+"

   a 是追加 a+ 追加

1 a_file = open("a.txt","a",encoding="utf-8")
2 a_file.write("555\n")
3 a_file.close()
4 
5 a_file1 = open("a.txt", "a+", encoding="utf-8")
6 a_file1.write("333\n")
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"))

 

posted on 2021-01-12 16:39  咫尺天涯$  阅读(92)  评论(0编辑  收藏  举报