【第5天】python全栈从入门到放弃

1.文件操作r模式

代码块
with open('goal',mode='r',encoding='utf-8') as f:
    res=f.read(3)  #read()这里括号的单位是字符。
    print(res)    #打印文件中的内容

2.文件操作w模式

该模式(w)不是追加,会清空掉文件之前的内容,重新写内容

代码块
with open('goal',mode='w',encoding='utf-8') as f:
    res=f.write('hello王思雨')
    f.flush()

3.文件操作a模式,追加模式

代码块
with open('goal',mode='a',encoding='utf-8') as f:
    res=f.write('时光不负赶路人')
    f.flush()

4.文件操作rb模式,处理非文本文件

b代表bytes,所以后面不用跟encoding='utf-8'

代码块
with open('goal',mode='rb') as f:
    res=f.read()
    print(res.decode('utf-8'))   #hello王思雨时光不负赶路人

5.文件操作wb模式,处理非文本(会完全覆盖清空指点写的内容)

代码块
with open('goal',mode='wb') as f:
    res=f.write('关于梦想'.encode('utf-8'))
    f.flush()

6.文件操作模式ab模式

代码块
with open('goal',mode='ab') as f:
    res=f.write('我从来没有放弃'.encode('utf-8'))
    f.flush()

7.文件操作R+模式(先读后写)

深坑:在没有读f.read()操作之前,R+写在最初光标的开始,如果有任何读取的操作,写的内容都在末尾,一定要注意了。

代码块
with open('goal',mode='r+',encoding='utf-8') as f:
    res=f.read()
    f.write('狗日的青春')
    f.flush()

8.seek()光标移动(单位是字节),read()括号单位是字符,注意,一个是字符,一个是字节

seek(0)光标移动到开头

seek(0,2)光标移动到末尾

代码块
with open('goal',mode='r+',encoding='utf-8') as f:
    res=f.read()
    f.write('谁的青春不迷茫')   #在末尾添加
    f.seek(3)     #从头开始,将光标向后移动3个字节。
    res=f.read(3)  #在这里读取三个字符,注意,是字符
    print(res)     

9.文件内容的替换和文件名的重命名

代码块
import os

with open('goal', mode='r', encoding='utf-8') as f1, open('new_goal', mode='w', encoding='utf-8') as f2:
    s = f1.read()
    s2 = s.replace('的', '钱')
    f2.write(s2)
    f2.flush()

os.remove('goal')
os.renames('new_goal','goal')
别跑,点个赞再走
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容