python
io
1. w写入 重复执行之前的内容会被覆盖
my_string='hello world26,'
a=open('data01.txt','w') # 建立一个a通道
a=open('data01.txt','a') 不会被覆盖
a.write(my_string) # 将my_string字符串写入到data01.txt中
2.r读出
my_string='hello world26,'
b=open('data02.txt','r')
con=b.read() # 读出内容
print(con)
3.w+可写可读 优先执行写
b=open('data01.txt','w+')
b.write(my_string) #将my_string写入
#加上b.seek(0)可以读出,光标被提前
con=b.read()
print(con) #此时读不出内容 因为光标在最后
4.wb 以字节码写入
a=open('data01.txt','wb')
a.write(my_string) #出错
a.write(my_string.encode()) #正常写入,内容还是原内容不是字节码
5.rb 以字节码读出
a=open('data01.txt','rb')
print(c) # 输出字节码
print(c.decode()) #正常读出
6.json.dumps()#将python对象转化为json字符串
json.loads()#将json字符串转化为python对象
import json
users=[
{"id":'0013中国',"user_name":"admin","user_password":"123","birthday":"20180-3-1"},
{"id":'002',"user_name":"test","user_password":"123","birthday":"2012-4-1"},
{"id":'003',"user_name":"boss","user_password":"666","birthday":"2007-5-1"}
]
s=json.dumps(users) 将字典转化为json字符串写入
fp=open('a.txt','w')
fp.write(s)
a=open('a.txt','r')
con=json.loads(a)
print(con) 读出
=======================
这样读出若有中文会出现字节码
b=open('a.txt','r')
c=b.read()
print(c)
6.json序列化
import json
users=[
{"id":'001',"user_name":"admin","user_password":"123","birthday":"20180-3-1"},
{"id":'002',"user_name":"test","user_password":"123","birthday":"2012-4-1"},
{"id":'003',"user_name":"boss","user_password":"666","birthday":"2007-5-1"}
]
a=open('a.json','w')
json.dump(users,a) 将json序列化写入
b=open('a.json','r')
con=json.load(b) 将json反序列化读出
print(con)
```
7.目录 ./当前目录 ../上一级目录
```
import json
users=[
{"id":'001',"user_name":"admin","user_password":"123","birthday":"20180-3-1"},
{"id":'002',"user_name":"test","user_password":"123","birthday":"2012-4-1"},
{"id":'003',"user_name":"boss","user_password":"666","birthday":"2007-5-1"}
]
fp=open('./w.txt','w') 写在当前目录下
json.dump(users,fp)
fp=open('./../w.txt','w') 写在上一级目录下
json.dump(users,fp)
8.生成文件名不同的文件
import time
import random
my_time=time.time()
number=random.random()
file_name=my_time+number 将时间戳与随机数之和作为文件名,避免重名
a=open('./../'+str(file_name)+'.txt','w')
a.write() 会生成许多不同文件名的文件
8.flush() 缓冲
若写入两个文件在中间使用flush将上面的文件送走
import json
users=[
{"id":'001',"user_name":"admin","user_password":"123","birthday":"20180-3-1"},
{"id":'002',"user_name":"test","user_password":"123","birthday":"2012-4-1"},
{"id":'003',"user_name":"boss","user_password":"666","birthday":"2007-5-1"}
]
a=open('q.json','w')
json.dump(users,a)
list=[1,2,3,4]
a.flush()
json.dump(list,a)
9.readline 按行读
a=open('1.txt','r')
c=a.readline() 读出第一行 1
c=a.readline() 读出第二行 2
print(c)
print(a.tell())
c=a.readlines() 一行读出['1\n', '2\n', '3\n', '4']
10.内存读写
#写入内存 临时存储在取出来 省掉定义变量
from io import StringIO,BytesIO
my_str='abcdefg'
fp=StringIO()
fp.write(my_str[::-1])#存入内存
str=my_str+fp.getvalue()#取出来
print(str)
BytesIO以二进制写入
fp_btye=BytesIO()
fp_btye.write('中国'.encode())#转化成字节码存入
print(fp_btye.getvalue()) #b'\xe4\xb8\xad\xe5\x9b\xbd'
print(fp_btye.getvalue().decode())#中国 解码输出