Learning experience _ file operation !!

File operations

Read the three states file

The first value of mode

r read-only (read-only files)

with open(r"a.txt",mode='r',encoding='utf8') as rf:

w write-only (no it is created, there will be emptied)

with open(r"a.txt",mode='w',encoding='utf8') as wf:

a append (no create, there is appended)

with open(r"a.txt",mode='a',encoding='utf8') as af:

The second value of mode

1 t text represented in text mode write mode (default mode t) (must not be used alone and in combination rwa)

with open(r"a.txt",mode='rt',encoding='utf8') as rtf:

2 b binary pattern represented in binary write mode (as binary mode without encoding attribute)

(Must not be used alone and in combination rwa)

with open(r'a.exe',mode='rb') as rbf:

Copies of documents

A copy of a movie

import os
with open(r'C:\Users\wu_oldBoy\Desktop\JoJo31.mp4',
          mode='rb') as readmovie, \ #因为电影不是文本文件 所以用'rb'读取,写也是用'wb'
    open(r"C:\Users\wu_oldBoy\Desktop\JoJo31copy.mp4",mode="wb") as newmovie:
    for i in readmovie:
        newmovie.write(i) #测试md5值一致,拷贝成功
#替换掉原有文件 (虽然只是复制了文件)
os.remove('C:\Users\wu_oldBoy\Desktop\JoJo31.mp4') 
os.rename('C:\Users\wu_oldBoy\Desktop\JoJo31copy.mp4','C:\Users\wu_oldBoy\Desktop\JoJo31.mp4')

Guess you like

Origin www.cnblogs.com/blog5434/p/10939666.html