1.IO读写:
文件读:
方法一:
f = open('D:/test.txt', 'r', encoding='GBK', errors='ignore')
print(f.read())
f.read(size)#加个读取文件的大小
f.readline()#按行读取
f.readlines()#读取全部行
f.close()#关闭读取文件
方法二:
with open('D:/test.txt', 'r') as f:
f.read()
文件写:
with open('D:/test.txt', 'w') as f:#w是写并覆盖,a是追加,两个不能同时用。
f.write()
2.在内存中读写,StringIO和BytesIO
StringIO:
from io import StringIO
f = StringIO('hello!
world!
')
while True:
s = f.readline()
if s =='':
break
print(s.strip())
f.write('我他娘在这里SB')
print(f.getvalue())
运行结果:
hello!
world!
hello!
world!
我他娘在这里SB
BytesIO:
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
f1= BytesIO(b'xe4xb8xadxe6x96x87')
print(f1.read())
运行结果:
b'xe4xb8xadxe6x96x87'
b'xe4xb8xadxe6x96x87'
3.文件和目录操作:
#操作系统
print(os.name)
#print(os.uname())
#环境变量
print(os.environ)#获取环境变量
print(os.environ.get('PATH'))#获取环境变量PATH
#操作文件和目录
print(os.path.abspath('.'))#当前文件绝对路径
#在某个文件夹下创建一个文件夹
s=os.path.join('d:/','pytest')
print(s)
os.mkdir(s)
os.rmdir(s)
print(os.path.split('/Users/michael/testdir/file.txt'))
print(os.path.splitext('/Users/michael/testdir/file.txt'))
# 对文件重命名:
os.rename('test.txt', 'test.py')
# 删掉文件:
os.remove('test.py')
拷贝文件:
import shutil
shutil.copyfile()
#列出当前目录下的所有目录,只需要一行代码:
print(os.path.isdir('d:/'))
#要列出所有的.py文件,也只需一行代码:
print([x for x in os.listdir('.')if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])
4.序列化pickling
方式一:pickle
pickle.dumps(d)
pickle.loads(d)
pickle.dump(d,f)
pickle.load(f)
方式二:json进阶,序列化类class和反序列化需要定制化参数
序列化:
def student2dict(stu):
return {
'name':stu.name,
'age':stu.age
}
json.dumps(s,default=student2dict)
或偷懒做法:json.dumps(s,default=lambda obj:obj.__dict__)
反序列化:
def dict2student(d):
return Student(d['name'],d['age'])
json.dumps(s,default=dict2student)