读
写
with open(path, mode, encoding) as file:
"""
打开源文件、目标文件
读取源文件,写入目标文件
关闭源文件、目标文件
"""
# 复制文本文件
# file = open('data.txt', 'a+', encoding='utf-8')
# # 0表示把指针放到文本最前面
# file.seek(0)
# msg = file.read()
# file.close()
# file = open('data.txt', 'r', encoding='utf-8')
# msg = file.read()
# file.close()
#
# file = open('data_bak.txt', "w", encoding='utf-8')
# file.write(msg)
# file.close()
# 复制图片
with open('imgs/train/snower.jpg', 'rb') as oriFile:
oriPic = oriFile.read()
with open('imgs/val/snower_bak.jpg', 'wb') as cyFile:
cyFile.write(oriPic)
import os
# 获取目录下的文件或文件夹
# print(os.listdir('./t123'))
# ['snower.jpg', 'snower_bak.jpg']
# print(os.listdir('../day08'))
# ['02-模块导入.py', '03-文件写入.py', '04-文件读取.py', '05-模式.py',
# '06-注册+登录用户.py', '07-复制文件.py', '08-os模块.py', 'data.txt',
# 'data_bak.txt', 't123', 'sort.py', 'user.txt', '__pycache__']
# 判断是目录还是文件
# print(os.path.isdir('./t123'))
# True
# print(os.path.isfile('./sort.py'))
# True
# 判断文件是否存在
# print(os.path.exists('./t123/val'))
# False
# if not os.path.exists('./t123/val'):
# # 创建
# os.mkdir('./t123/val')
# print(os.path.exists('../../test.py'))
# True
# 拼接路径
# print(os.path.join('t123', 'val'))
# t123\val
# print(os.path.join('t123', 'val', 'data.txt'))
# t123\val\data.txt
# 删除文件,不支持删除目录
# os.remove('./t123/snower_bak.jpg')
# os.remove('./t123/val')
# PermissionError: [WinError 5] 拒绝访问。: './t123/val'
# 重命名
# os.rename('./t123/train/snower.jpg', './t123/train/snow.jpg')
# os.rename('./t123/train/snow.jpg', './t123/train/snower.jpg')
python object --> json str
json str --> python object
"""
JSON语法
数据使用key:value形式表示
大括号表示对象
{
"name": "Anna",
"age": 18,
"hobbies": ['摄影', '阅读']
}
中括号表示多个
[
{
"name": "Anna",
"age": 18,
"hobbies": ['摄影', '阅读']
},
{
"name": "Emma",
"age": 19,
"hobbies": ['敲代码', '阅读']
}
]
转码解码
python object --> json
json.dumps()
json --> python object
json.loads()
"""
import json
dic = {
"name": "张三",
"age": 19
}
# 文件写入
# file = open('name.txt', 'a', encoding='utf-8')
# # python对象转为json字符串
# dic_json = json.dumps(dic)
# file.write(dic_json + '\n')
# file.close()
# {"name": "Anna", "age": 18}
# {"name": "\u5f20\u4e09", "age": 19}
# 文件读取
file = open('name.txt', 'r', encoding='utf-8')
lines = file.readlines()
for line in lines:
# json字符串转为python对象
dic = json.loads(line)
print(dic['name'], dic['age'])
file.close()
# Anna 18
# 张三 19
python object --> yaml str
yaml str --> python object
import yaml
# 读取yaml文件
# with open('./test.yaml', 'r', encoding='utf-8') as file:
# dic = yaml.safe_load(file)
# print(dic)
# {'name': 'Anna', 'age': 19, 'hobbies': ['摄影', '阅读']}
# 写入yaml文件
dic = {
'name': 'Emma',
'age': 18,
'hobbies': ['敲代码', '阅读']
}
with open('test2.yaml', 'w', encoding='utf-8') as file:
yaml.safe_dump(dic, file)
# age: 18
# hobbies:
# - "\u6572\u4EE3\u7801"
# - "\u9605\u8BFB"
# name: Emma
继承threading.Thread
"""
开启线程
线程执行任务(功能):
函数
创建线程 (线程也是对象)
开启线程
自定义线程类
"""
import threading
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
def task(self, *args):
name = threading.current_thread().name
print(threading.current_thread())
print(f'{name}正在执行任务 参数是:{args}')
def run(self):
print(f'run方法被执行 {threading.current_thread()}')
self.task('Anna', 18)
pass
if __name__ == '__main__':
# 创建线程
th = MyThread()
# th.task('Anna', 18)
th.start()
# run方法被执行
#
# Thread-1正在执行任务 参数是:('Anna', 18)
多个线程共享数据
lock 锁门操作
"""
卖票案例
多线程共享数据:出现线程安全问题,本质是多个线程对共享数据进行了修改
"""
import threading
import time
ticket = 100
lock = threading.Lock()
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
def sale_ticket(self):
global ticket
# 底层汇编语言执行步骤
# 第一步:获得票数 100
# 第二步:数据进行-1
# 第三步:减去的数据进行赋值
# 获取锁
lock.acquire()
if ticket < 1:
lock.release()
return False
ticket -= 1
# 模拟延时
time.sleep(0.01)
# 释放锁
lock.release()
name = threading.current_thread().name
print(f'{name}卖了1张票,还剩下{ticket}张')
return ticket > 0
def run(self):
while self.sale_ticket():
pass
if __name__ == '__main__':
for i in range(3):
# 创建线程
th = MyThread()
th.name = f'th{i}'
# 启动线程
th.start()
无法正确运行的代码,编译器会出现红色报错提示,这个错误提示即是异常
"""
异常
"""
print('start')
# ZeroDivisionError: division by zero
# ZeroDivisionError --> ArithmeticError --> Exception --> BaseException --> object
print(2 / 0)
print('end')
"""
异常捕获
try:
try写容易报错的代码
except 报错类型:
代码报错时,except写处理的代码
finally:
无论try except代码是否被执行,finally代码都会被执行
报错类型写法
具体错误类型
多个错误类型组成的元组
Exception
"""
print('start')
file = None
# ZeroDivisionError: division by zero
# ZeroDivisionError --> ArithmeticError --> Exception --> BaseException --> object
try:
# num = 2 / 0
# print(name)
file = open('data.txt', 'r', encoding='utf-8')
# 很多代码
# 模拟异常
num = 2 / 0
# except ZeroDivisionError:
# print('ZeroDivisionError')
# pass
# except NameError:
# print('NameError')
# pass
# except (NameError, ZeroDivisionError) as e:
# print(f'NameError {e}')
# NameError name 'name' is not defined
except Exception as e:
print(f'Exception {e}')
finally:
print('执行了finally')
print('关闭文件')
if file:
file.close()
pass
print('end')
"""
自定义异常
"""
class AngryError(Exception):
def __init__(self, msg):
super(AngryError, self).__init__(msg)
if __name__ == '__main__':
try:
print('no moive')
raise AngryError('so angry')
except AngryError as e:
# print(e)
print(f'{type(e).__name__}: {e}')
# no moive
# AngryError: so angry
"""
枚举
元素不允许重复、不允许被外部修改变量值
元素使用类名.变量名调用
"""
from enum import IntEnum, Enum
# class Transpose(IntEnum):
# FLIP_LEFT_RIGHT = 0
# FLIP_TOP_BOTTOM = 1
# ROTATE_90 = 2
# ROTATE_180 = 3
# ROTATE_270 = 4
# TRANSPOSE = 5
# TRANSVERSE = 6
#
#
# print(Transpose.FLIP_TOP_BOTTOM.name)
# # FLIP_TOP_BOTTOM
# print(Transpose.FLIP_TOP_BOTTOM.value)
# # 1
# print(Transpose.FLIP_TOP_BOTTOM == 1)
# # True
class ImageType(Enum):
TRAIN_TYPE = 'train'
TEST_TYPE = 'test'
print(ImageType.TRAIN_TYPE.name)
# TRAIN_TYPE
print(ImageType.TRAIN_TYPE.value)
# train