廖雪峰Python学习笔记day8

客官°小女子只卖身不卖艺 2022-12-25 03:53 255阅读 0赞

学习笔记day7

  1. # python study day8
  2. # IO编程
  3. # 1、基本概念:input、output、stream
  4. # 2、存在问题:输入和接收速度不匹配
  5. # 3、解决方法:同步、异步(回调--好了叫我,轮询--好了没...好了没)
  6. # 4、其它:编程语言都会把操作系统提供的低级C接口封装起来方便使用
  7. # 文件读写
  8. # try:
  9. # # r:以读的方式打开,w:以写的方式打开
  10. # # rb:二进制读取图片视频等
  11. # f = open('/path/to/file','r')
  12. # # read():读取所有,read(size): 每次读size,readline():读一行
  13. # # readlines():读所有,按行返回
  14. # print(f.read())
  15. # finally:
  16. # if f:
  17. # f.close() # 释放资源
  18. # 添加其他参数(error遇到错误如何处理)
  19. # f = open('/Users/michasel/gbk.txt', 'r', encoding='gbk', errors='ignore')
  20. # python引入with语句自动调用close()方法
  21. # with open('/path/to/file', 'r') as f:
  22. # print(f.read())
  23. # with open('/Users/temp/test.txt', 'w') as f: # w覆盖写入,a(append):追加写入
  24. # f.write('Hi, world!')
  25. # StringIO: 内存读写字符串;BytesIO: 内存读写二进制
  26. # from io import StringIO, BytesIO
  27. # f1 = StringIO('ss')
  28. # f1.write('hi')
  29. # f1.write('world')
  30. # print(f1.getvalue()) #>>> hiworld
  31. # f2 = BytesIO('中文'.encode('utf-8'))
  32. # print(f2.getvalue()) #>>>b'\xe4\xb8\xad\xe6\x96\x87'
  33. # from io import StringIO
  34. # f = StringIO('Hello!\nHi!\nGoodbye!')
  35. # while True:
  36. # s = f.readline()
  37. # if s == '':
  38. # break
  39. # print(s.strip())
  40. # # Hello!
  41. # # Hi!
  42. # # Goodbye!
  43. # 操作文件和目录,python封装了os模块,有些在os.path中(有些函数和系统相关)
  44. # import os
  45. # os.name #>>> 操作系统类型,nt Windows
  46. # os.uname #>>> 纤细系统信息,windows不支持
  47. # os.environ #>> 环境变量
  48. # os.environ.get('key') #>>> 获取环境变量
  49. # os.path.abspath('.') #>>> 查看当前目录绝对路径
  50. # os.path.join('Users/gan', 'testdir') #>>> 根据系统拼接完整路径(文件分隔符不同)
  51. # os.mkdir('Users/gan/testdir') #>>> 创建目录
  52. # os.rmdir('Users/gan/testdir') #>>> 删除目录
  53. # os.path.split('/Users/gan/testdir/file.txt')
  54. # # 拆分目录文件名 >>> ('/Users/michael/testdir', 'file.txt')
  55. # os.path.splitext('/path/to/file.txt')
  56. # # 可以直接获取文件扩展名 >>> ('/path/to/file', '.txt')
  57. # os.rename('test.txt', 'test.py') #>>> 文件重命名
  58. # os.remove('test.py') #>>> 删除文件
  59. # # shutil模块提供了copyfile()函数拷贝文件
  60. # [x for x in os.listdir('.') if os.path.isdir(x)] #>>> 列出当前目录所有目录
  61. # [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
  62. # #>>> 列出所有.py文件
  63. # from datetime import datetime # dir -l 效果
  64. # import os
  65. # pwd = os.path.abspath('.')
  66. # print(' Size Last Modified Name')
  67. # print('------------------------------------------------------------')
  68. # for f in os.listdir(pwd):
  69. # fsize = os.path.getsize(f)
  70. # mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M')
  71. # flag = '/' if os.path.isdir(f) else ''
  72. # print('%10d %s %s%s' % (fsize, mtime, f, flag))
  73. # # Size Last Modified Name
  74. # ------------------------------------------------------------
  75. # 63 2018-12-11 16:17 .babelrc
  76. # 2377 2018-12-11 16:17 .flowconfig
  77. # 0 2019-07-20 14:30 .git/
  78. # 17 2018-12-11 16:17 .gitattributes
  79. # 当前目录查找文件
  80. # import os
  81. # def searchFile(str, path='.'):
  82. # for x in os.listdir(x):
  83. # if os.path.isdir(x):
  84. # newPath = os.path.join(path, x)
  85. # searchFile(str, newPath) # 递归查找
  86. # else:
  87. # if str in x:
  88. # print(os.path.join(path, x))
  89. # 序列化 pickling:把变量从内存变成可存储或传输的过程。java中为serialization
  90. # 反序列化 unpickling:把内容从序列化的对象重新读到内存里
  91. # import pickle
  92. # d = dict(name='Alice', age=18, score=88.5)
  93. # pickle.dumps(d) # 序列化对象
  94. # with open('dump.txt', 'wb') as f:
  95. # pickle.dump(d, f) # bytes写入文件
  96. # with open('dump.txt', 'rb') as f:
  97. # d = pickle.load(f) # 反序列化对象
  98. # python对象和JSON格式转换
  99. # import json
  100. # d = dict(name='Alice', age=18, score=88.5)
  101. # print(json.dumps(d)) #>>> {"name": "Alice", "age": 18, "score": 88.5}
  102. # json_str = '{"age": 18, "score": 88.5, "name": "Alice"}'
  103. # print(json.loads(json_str)) #>>> {'age': 18, 'score': 88.5, 'name': 'Alice'}
  104. # 类对象序列化
  105. # import json
  106. # class Student(object):
  107. # def __init__(self, name,age, score):
  108. # self.name = name
  109. # self.age = age
  110. # self.score = score
  111. # s = Student('Alice', 18, 88.5)
  112. # def student2dict(std):
  113. # return {
  114. # 'name': std.name,
  115. # 'age': std.age,
  116. # 'score': std.score
  117. # }
  118. # print(json.dumps(s, default=student2dict))
  119. # print(json.dumps(s, default=lambda obj: obj.__dict__))
  120. #>>> {"name": "Alice", "age": 18, "score": 88.5}
  121. # def dict2student(d):
  122. # return Student(d['name'], d['age'], d['score'])
  123. # json_str = '{"age": 18, "score": 88.5, "name": "Alice"}'
  124. # print(json.loads(json_str, object_hook=dict2student)) # 反序列化对象
  125. #>>> <__main__.Student object at 0x00000239949E7160>

在这里插入图片描述
学习笔记day9

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读