day-06 文件读写

# # -*- coding: utf-8 -*-
''' r 读 w 写 a 追加写
r+ 读写 w+ 读写 a+读写
rb 读字节 wb 写字节
w r 是文本 rb wb非文本
../ (相对路径)上一层 ../../ (上两层)
'''

'''r 模式 只能读,不能写入内容'''
f=open('文件',mode='r',encoding='utf-8')
# f.write('hello') #无法写入 hello
# f.colse()
print(f)

'''w 模式 写入之前清楚原有内容,若没有文件则新建并写入内容'''
f=open('文件',mode='r',encoding='utf-8')
f.write('hello')
f.flush() #刷新
f.close()

'''a 模式 在末尾追加写入内容'''
f=open('文件',mode='a',encoding='utf-8')
f.write('hello')
f.close()

'''r+ 模式 光标在文件开头,先读后写,若先写后读,写入多少内容就会覆盖文件前面多少内容,
无操作前写入内容,会在文件开头写入,若读取了一些内容(不管读取多少内容),写入内容会在末尾
写入内容后读取不到文件内容,需重新定义光标,将光标定义在文件开头 用.seek()定位光标,0表示开头(0,0),1表示当前(0,1),2表示末尾(0,2)'''
f=open('文件',mode='r+',encoding='utf-8')
f.read() # 读取内容
f.write() # 写内容
f.flush() # 刷新
f.close() # 关闭

'''w+ 模式 无seek()无法读取内容,一定要加seek(),写入之前清楚原有内容,若没有文件则新建并写入内容'''
f=open('文件',mode='w+',encoding='utf-8')
f.write() # 写内容
f.seek(0,0) #重新定位光标到文件开头
f.read() # 读取内容
f.close() # 关闭

'''os 模式'''
import os
#将文件,打开写入内容到文件_副本
with open('文件',mode='r',encoding='utf-8')as f1,open('文件_副本',mode='w',encoding='utf-8')as f2:
s=f1.read() # 读取
ss=s.replace('你好','hello') #将"你好"替换成"hello"
f2.write(ss) # 将ss的文件内容写入
os.remove('文件') #删除文件名
os.rename('文件_副本','文件1') #将"文件_副本"重命名为"文件1"
原文地址:https://www.cnblogs.com/puti306/p/10122240.html