廖雪峰Python学习笔记day8
学习笔记day7
# python study day8
# IO编程
# 1、基本概念:input、output、stream
# 2、存在问题:输入和接收速度不匹配
# 3、解决方法:同步、异步(回调--好了叫我,轮询--好了没...好了没)
# 4、其它:编程语言都会把操作系统提供的低级C接口封装起来方便使用
# 文件读写
# try:
# # r:以读的方式打开,w:以写的方式打开
# # rb:二进制读取图片视频等
# f = open('/path/to/file','r')
# # read():读取所有,read(size): 每次读size,readline():读一行
# # readlines():读所有,按行返回
# print(f.read())
# finally:
# if f:
# f.close() # 释放资源
# 添加其他参数(error遇到错误如何处理)
# f = open('/Users/michasel/gbk.txt', 'r', encoding='gbk', errors='ignore')
# python引入with语句自动调用close()方法
# with open('/path/to/file', 'r') as f:
# print(f.read())
# with open('/Users/temp/test.txt', 'w') as f: # w覆盖写入,a(append):追加写入
# f.write('Hi, world!')
# StringIO: 内存读写字符串;BytesIO: 内存读写二进制
# from io import StringIO, BytesIO
# f1 = StringIO('ss')
# f1.write('hi')
# f1.write('world')
# print(f1.getvalue()) #>>> hiworld
# f2 = BytesIO('中文'.encode('utf-8'))
# print(f2.getvalue()) #>>>b'\xe4\xb8\xad\xe6\x96\x87'
# from io import StringIO
# f = StringIO('Hello!\nHi!\nGoodbye!')
# while True:
# s = f.readline()
# if s == '':
# break
# print(s.strip())
# # Hello!
# # Hi!
# # Goodbye!
# 操作文件和目录,python封装了os模块,有些在os.path中(有些函数和系统相关)
# import os
# os.name #>>> 操作系统类型,nt Windows
# os.uname #>>> 纤细系统信息,windows不支持
# os.environ #>> 环境变量
# os.environ.get('key') #>>> 获取环境变量
# os.path.abspath('.') #>>> 查看当前目录绝对路径
# os.path.join('Users/gan', 'testdir') #>>> 根据系统拼接完整路径(文件分隔符不同)
# os.mkdir('Users/gan/testdir') #>>> 创建目录
# os.rmdir('Users/gan/testdir') #>>> 删除目录
# os.path.split('/Users/gan/testdir/file.txt')
# # 拆分目录文件名 >>> ('/Users/michael/testdir', 'file.txt')
# os.path.splitext('/path/to/file.txt')
# # 可以直接获取文件扩展名 >>> ('/path/to/file', '.txt')
# os.rename('test.txt', 'test.py') #>>> 文件重命名
# os.remove('test.py') #>>> 删除文件
# # shutil模块提供了copyfile()函数拷贝文件
# [x for x in os.listdir('.') if os.path.isdir(x)] #>>> 列出当前目录所有目录
# [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
# #>>> 列出所有.py文件
# from datetime import datetime # dir -l 效果
# import os
# pwd = os.path.abspath('.')
# print(' Size Last Modified Name')
# print('------------------------------------------------------------')
# for f in os.listdir(pwd):
# fsize = os.path.getsize(f)
# mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M')
# flag = '/' if os.path.isdir(f) else ''
# print('%10d %s %s%s' % (fsize, mtime, f, flag))
# # Size Last Modified Name
# ------------------------------------------------------------
# 63 2018-12-11 16:17 .babelrc
# 2377 2018-12-11 16:17 .flowconfig
# 0 2019-07-20 14:30 .git/
# 17 2018-12-11 16:17 .gitattributes
# 当前目录查找文件
# import os
# def searchFile(str, path='.'):
# for x in os.listdir(x):
# if os.path.isdir(x):
# newPath = os.path.join(path, x)
# searchFile(str, newPath) # 递归查找
# else:
# if str in x:
# print(os.path.join(path, x))
# 序列化 pickling:把变量从内存变成可存储或传输的过程。java中为serialization
# 反序列化 unpickling:把内容从序列化的对象重新读到内存里
# import pickle
# d = dict(name='Alice', age=18, score=88.5)
# pickle.dumps(d) # 序列化对象
# with open('dump.txt', 'wb') as f:
# pickle.dump(d, f) # bytes写入文件
# with open('dump.txt', 'rb') as f:
# d = pickle.load(f) # 反序列化对象
# python对象和JSON格式转换
# import json
# d = dict(name='Alice', age=18, score=88.5)
# print(json.dumps(d)) #>>> {"name": "Alice", "age": 18, "score": 88.5}
# json_str = '{"age": 18, "score": 88.5, "name": "Alice"}'
# print(json.loads(json_str)) #>>> {'age': 18, 'score': 88.5, 'name': 'Alice'}
# 类对象序列化
# import json
# class Student(object):
# def __init__(self, name,age, score):
# self.name = name
# self.age = age
# self.score = score
# s = Student('Alice', 18, 88.5)
# def student2dict(std):
# return {
# 'name': std.name,
# 'age': std.age,
# 'score': std.score
# }
# print(json.dumps(s, default=student2dict))
# print(json.dumps(s, default=lambda obj: obj.__dict__))
#>>> {"name": "Alice", "age": 18, "score": 88.5}
# def dict2student(d):
# return Student(d['name'], d['age'], d['score'])
# json_str = '{"age": 18, "score": 88.5, "name": "Alice"}'
# print(json.loads(json_str, object_hook=dict2student)) # 反序列化对象
#>>> <__main__.Student object at 0x00000239949E7160>
学习笔记day9
还没有评论,来说两句吧...