r模式:只读 d模式:写模式(写的新内容会把旧的内容删掉) a模式:写模式(新的内容不会将旧的内容删掉) rb模式:读取内容是字节(可处理非文本) wb模式:写字节(可处理非文本) ab模式:追加字节(可处理非文本) r+模式:读写模式(注意先读再写)
举例:
r模式:f =open("haha.txt" , mode="r",encoding="utf-8")s = f.read()f.close() #关闭句柄print(s) rb模式:f =open("haha.txt" , mode="rb") #读取的内容直接是字节bs = f.read()print(bs.decode("utf-8")) #需要解码f.close() wb模式:f = open("haha.txt",mode="wb")f.write("嘻嘻".encode("utf-8"))f.close() #r+模式:f = open("haha.txt",mode = "r+",encoding = "utf-8")# s = f.read(3)# f.write("呵呵") #不管前面读了几个,后面写的都在末尾# print(s)f.write("嘿嘿") #1、什么都不做直接写的是在开头写 2、如果读取了之后再写是在最后写 f.seek(0) #移动到开头位置f.seek(3) #移动三个字节即一个汉字f.seek(0,2) #移动到末尾 第二个参数有三个值:0在开头;1在当前;2在末尾 #嘿嘿哈哈呵呵f = open("haha.txt", mode="r+", encoding="utf-8")f.seek(3) #移动3个字节s=f.read(3) #读取3个字print(s)#结果:嘿哈哈 #文件修改import oswith open("haha.txt", mode="r",encoding="utf-8") as f1,\open("haha_副本.txt", mode="w",encoding="utf-8") as f2: s = f1.read() ss = s.replace("哈","吃") #将哈改成吃 f2.write(ss) #将修改后的字符串放入副本中os.remove("haha.txt") #删除haha.txt文件os.rename("haha_副本.txt","haha.txt") #将haha_副本.txt改成haha.txt #按行进行文件修改import oswith open("haha.txt", mode="r",encoding="utf-8") as f1,\ #这种写法后面不需要closeopen("haha_副本.txt", mode="w",encoding="utf-8") as f2:for line in f1: #一行数据 s = line.replace("吃","菜") #将哈改成吃 f2.write(s) #将修改后的字符串放入副本中os.remove("haha.txt") #删除haha.txt文件os.rename("haha_副本.txt","haha.txt") #将haha_副本.txt改成haha.txt转载于:https://www.cnblogs.com/xiaojingjingzhuanshu/p/11224834.html
