苏州网络推广,卓越精算,古董收藏
obj = open('路径',mode='模式',encoding='编码') obj.write() # 写入 obj.read() # 读取 obj.close() #关闭
read() , 全部读到内存
read(1)
1表示一个字符
obj = open('a.txt',mode='r',encoding='utf-8') data = obj.read(1) # 1个字符 obj.close() print(data)
1表示一个字节
obj = open('a.txt',mode='rb') data = obj.read(3) # 1个字节 obj.close()
write(字符串)
obj = open('a.txt',mode='w',encoding='utf-8') obj.write('中午你') obj.close()
write(二进制)
obj = open('a.txt',mode='wb') # obj.write('中午你'.encode('utf-8')) v = '中午你'.encode('utf-8') obj.write(v) obj.close()
seek(光标字节位置),无论模式是否带b,都是按照字节进行处理。
obj = open('a.txt',mode='r',encoding='utf-8') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data) obj = open('a.txt',mode='rb') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data)
tell(), 获取光标当前所在的字节位置
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳转到指定字节位置 obj.read() data = obj.tell() print(data) obj.close()
flush,强制将内存中的数据写入到硬盘
v = open('a.txt',mode='a',encoding='utf-8') while true: val = input('请输入:') v.write(val) v.flush() v.close()
文艺青年
v = open('a.txt',mode='a',encoding='utf-8') v.close()
二逼
with open('a.txt',mode='a',encoding='utf-8') as v: data = v.read() # 缩进中的代码执行完毕后,自动关闭文件
with open('a.txt',mode='r',encoding='utf-8') as f1: data = f1.read() new_data = data.replace('飞洒','666') with open('a.txt',mode='w',encoding='utf-8') as f1: data = f1.write(new_data)
大文件修改
f1 = open('a.txt',mode='r',encoding='utf-8') f2 = open('b.txt',mode='w',encoding='utf-8') for line in f1: new_line = line.replace('阿斯','死啊') f2.write(new_line) f1.close() f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2: for line in f1: new_line = line.replace('阿斯', '死啊') f2.write(new_line)
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论