对文件的各种操作

1 read(读),write(覆盖写),add(追加)

f = open('文件名',mode = 'r',encoding= 'utf-8')#第一个参数是要操作的文件的名字
                            #第二个参数选择的模式'r''w''a'等
                            #第三个参数自定义的编码集

 read(读):只读 不进行其他操作.

f = open('tt',mode 1= 'r',encoding= 'utf-8') #对文件tt进行读操作,不能进行其他操作
  f.read()

 write(写):覆盖写,不进行其他操作.写之前会先清空文件的内容,文件不存在的时候会创建一个文件

f =open('tt',mode='w',encoding='utf-8') #清空完文件tt的内容,然后再写进去
  f.write('写的内容')

 add(追加写):在文件内容的末尾进行追加内容

f= open('tt',mode='a',encoding='utf-8') #在tt文件的内容中追加内容
  f.write('追加的内容')

 将一个文件进行备份操作:

with open('tt',mode="r",encoding='utf-8') as f:
    msg = f.read()
with open('nn',mode='a',encoding='utf-8')as f1:
    f1.write(msg)

2,r+(读,写),w+(写,读),a+(追加写,读)

  2.1 r+  读 写

    mode = r+时,必须进行先读后写操作,不然文件会被错误改动

  2.2 w+ 写 读

    mode = w+时,写读的时候,必须移动光标seek(0),才能完整读出内容

  2.3 a+  追加写 读 

    mode =a+时,写读的时候,必须移动光标seek(0),才能完整读出内容

3.其他操作

f = open('tt',mode= 'r',encoding='utf-8')#必须需要结束 
f.close()

with open('tt',mode='r',encoding='utf-8') as f: #不需要结束

  seek() 移动光标

  参数为字节数 

  双个数字为see(0,0) 文件开头位置

  双个数字为see(0,1) 文件当前位置

  双个数字为see(0,2) 文件结尾位置

    

    

原文地址:https://www.cnblogs.com/shicongcong0910/p/10240770.html