【十二】Python-匿名函数-文件

回顾之前知识点

【作用域:LEGB】
L: local 本地  局部变量
E: encloseing  嵌套
G: Global  全局
B: built-in 内置的

【嵌套函数】
 闭包:
1. 内层函数
2. 内层函数引用外层函数的变量
3. 返出内层函数

装饰器:
1. 内层函数
2. 内层函数引用外层函数的变量
3. 返出内层函数
4. 函数作为外层函数参数

使用装饰器:
@装饰器名字
def 函数名():
    pass

匿名函数-lambda

# 匿名函数: 简化函数定义
# 格式:  lambda  参数1, 参数2.. : 运算

# def func():
#     print('aaaa')
#
#
def add(a, b):
    s = a + b
    return s

f = add

s = lambda a, b: a + b
print(s)  # s 就是函数function

result = s(1, 2)
print(result)

s1 = lambda x, y: x * y
result = s1(2, 5)
print(result)

# 匿名函数作为参数
def func(x, y, func):
    print(x, y)
    print(func)
    s = func(x, y)
    print(s)

# 调用func
func(1, 2, lambda a, b: a + b)

# 匿名函数与内置函数的结合使用:
# max  sorted   zip ...

list1 = [3, 5, 8, 9, 0]
m = max(list1)

print('列表的最大值:', m)

list2 = [{'a': 10, 'b': 20}, {'a': 13, 'b': 20}, {'a': 9, 'b': 20}, {'a': 29, 'b': 20}]

m = max(list2, key=lambda x: x['a'])
print('列表的最大值:', m)

'''
 students =[
 {'name':'tom','age':20},
 {'name':'lucy','age':19},
 {'name':'lily','age':13},
 {'name':'mark','age':21},
 {'name':'jack','age':23},
 {'name':'steven','age':18},
 ]

'''

匿名函数2

# 匿名函数: 简化函数定义
# 格式:  lambda  参数1, 参数2.. : 运算

# def func():
#     print('aaaa')
#
#
def add(a, b):
    s = a + b
    return s

f = add

s = lambda a, b: a + b
print(s)  # s 就是函数function

result = s(1, 2)
print(result)

s1 = lambda x, y: x * y
result = s1(2, 5)
print(result)

# 匿名函数作为参数
def func(x, y, func):
    print(x, y)
    print(func)
    s = func(x, y)
    print(s)

# 调用func
func(1, 2, lambda a, b: a + b)

# 匿名函数与内置函数的结合使用:
# max  sorted   zip ...

list1 = [3, 5, 8, 9, 0]
m = max(list1)

print('列表的最大值:', m)

list2 = [{'a': 10, 'b': 20}, {'a': 13, 'b': 20}, {'a': 9, 'b': 20}, {'a': 29, 'b': 20}]

m = max(list2, key=lambda x: x['a'])
print('列表的最大值:', m)

'''
 students =[
 {'name':'tom','age':20},
 {'name':'lucy','age':19},
 {'name':'lily','age':13},
 {'name':'mark','age':21},
 {'name':'jack','age':23},
 {'name':'steven','age':18},
 ]

'''

map() reduce() filter() sorted()

# map

list1 = [3, 4, 6, 7, 8, 9, 9, 0, 2, 5]

result = map(lambda x: x + 2, list1)
print(list(result))

# for index,i in enumerate(list1):
#     list1[index]=i+2

func = lambda x: x if x % 2 == 0 else x + 1

result = func(5)
print(result)

# 对列表中的奇数进行加1操作
result = map(lambda x: x if x % 2 == 0 else x + 1, list1)
print(list(result))

# for index, i in enumerate(list1):
#     if i % 2 != 0:
#         list1[index] = i + 1
#
# print(list1)


# reduce(): 对列表中的元素进行加减乘除运算的函数
# 根据后面的函数规则进行 加减乘除运算
from functools import reduce

tuple1 = (3, 5, 7, 8, 9, 1)
result = reduce(lambda x, y: x + y, tuple1)
print(result) #全部相加 33

tuple2 = (1,2,3)
#10 表示 初始值 10-1-2-3=4
result = reduce(lambda x, y: x - y, tuple2, 10)
print(result)

# 动手测试减法
list1 = [12, 6, 8, 98, 34, 36, 2, 8, 0]
result = filter(lambda x: x > 10, list1)
print(list(result)) #所有大于10 的放到列表中  [12,98,34,36]
print(list1)

# def func(list1):
#     list2 = []
#     for i in list1:
#         if i > 10:
#             list2.append(i)
#     return list2


students = [
    {'name': 'tom', 'age': 20},
    {'name': 'lucy', 'age': 19},
    {'name': 'lily', 'age': 13},
    {'name': 'mark', 'age': 21},
    {'name': 'jack', 'age': 23},
    {'name': 'steven', 'age': 18},
]

# 找出所有年龄大于20岁学生
result = filter(lambda x: x['age'] > 20,students)
print(list(result))

# 按照年龄从小到大排序
students = sorted(students,key=lambda x:x['age'],reverse=True)
print(students)

'''
max()  
min()
sorted()

map(): 
reduce()
filter()  

'''

递归函数

# 递归函数: 函数自己调用自己
'''
普通:def func():pass
匿名函数: lambda 参数: 返回结果
递归函数: 普通函数的一种表现形式

特点:
1. 递归函数必须要设定终点
2. 通常都会有一个入口
'''


def sum(n):  # 1~n
    '''
    求和的函数
    :param n: 从1~n累加和
    :return: 求和的结果
    '''
    if n == 0:
        return 0
    else:
        return n + sum(n - 1)


result = sum(10)
#
# print(result)

# def sum1(n):
#     if n==100:
#         pass
#     else:
#         pass



# s = 0
# for i in range(11):
#     s += i
# print(s)


def f1(n):
    if n>0:
        print('---->',n)
        f1(n - 1)
    else:
        print('----->',n)


f1(10)

# ----> 10
# ----> 9
# ----> 8
# ----> 7
# ----> 6
# ----> 5
# ----> 4
# ----> 3
# ----> 2
# ----> 1
# -----> 0

总结回顾函数

 

【总结函数】
普通函数:
   def 函数名([参数,...]):
        函数体

   1. 如何定义函数
   2. 调用函数

   参数:
   1. 无参数:
    def func():
        pass

    func()

   2. 有参数:
     一般参数:

     def func(a,b):
        pass

     func(1,2)

     可变参数:

     def func(*args,**kwargs):  args单个元素   kwargs 关键字参数
        pass

     func()

     func(1)

     func(a=10)

     默认值:

     def func(a=10,b=10):
        pass

     func()

     func(100)

     关键字参数:

     func(b=99)

   返回值: return

   没有返回值

   def func():
        print('-----')
   x= func()   ---->x=None


   有返回值:
   def func():
        return 'a'

   x =func()  -----> x ='a'

   def func():
        return 'a','b'

   x =func()  -----> x =('a','b')

嵌套函数  ---》 闭包  ---》 装饰器

def func():

    def wrapper():
        ....

    return wrapper

变量的作用域: LEGB
global    nonlocal
globals()  locals()
LEGB

L: local 本地  局部变量
E: encloseing  嵌套
G: Global  全局
B: built-in 内置的

装饰器:
单层装饰器

def decorate(func):
    def wrapper(*args,**kwargs):
        ....

    return wrapper

@decorate
def house():
    pass

@decorate
def f1(a,b):
    pass

多层装饰器:

@zhuang2
@zhuang1
def f1(a,b):
    pass


装饰器带参数:
def outter(a):
    def decorate(func):
        def wrapper(*args,**kwargs):
            ....

        return wrapper
   return decorate

@zhuang(10)
def house():
    pass

@zhuang(100):
def street():
    pass

匿名函数: lambda 参数:返回值

递归函数: 自己调用自己。

 文件打开、读取 read() readline() readlines()

# 文件操作:
'''
 文件上传
 保存log

系统函数:
 open(file,mode,buffering,encodeing)

mode: r w:读 写
      rb wb: binary二进制
 读:
   open(path/filename,'rt')---->返回值:stream (管道)

   container = stream.read()  ---->读取管道中内容

   注意: 如果传递的path/filename有误,则会报错:FileNotFoundError
    如果是图片则不能使用默认的读取方式,mode = 'rb'

    总结:
    read()  读取所有内容
    readline() 每次读取一行内容
    readlines() 读取所有的行保存到列表中
    readable()  判断是否可读的

'''
stream = open(r'C:\CA\file.txt')
# container = stream.read()
# print(container)

result = stream.readable()  # 判断是否可以读取  True  False
print(result)

# while True:
#     line = stream.readline()
#     print(line)
#     if not line:
#         break

lines = stream.readlines()  # 保存到列表中
print(lines)
for i in lines:
    print(i)

stream = open(r'C:\p1\girl.jpg', 'rb')

container = stream.read()
# print(container)

文件写入 write() writelines()

# 写文件
'''
stream = open(r'c:\p1\aa.txt', 'w')
mode 是’w‘ 表示就是写操作  每次都会将原来的内容清空,

方法:
    write(内容)   然后写当前的内容
    writelines(Iterable)  没有换行效果
    stream.writelines(['赌神高进\n', '赌侠小刀\n', '赌圣周星星\n'])  ---》自己加

如果mode='a',表示追加模式append
'''
stream = open(r'c:\p1\aa.txt', 'a')

# s = '''
# 你好!
#     欢迎来到澳门博彩赌场,赠送给你一个金币!
#                 赌王: 高进
#
# '''

result = stream.write('hello')
# print(result)

stream.write('龙五')

stream.writelines(['赌神高进\n', '赌侠小刀\n', '赌圣周星星\n'])

stream.write('僵尸先生')

stream.close()  # 释放资源

# stream.write('龙五2号')

文件复制

# 文件的复制
'''
原文件: c:\p1\girl.jpg
目标文件: c:\p2\girl.jpg

with 结合open使用,可以帮助我们自动释放资源

'''
# stream = open(r'c:\p1\girl.jpg', 'rb')

with open(r'c:\p1\girl.jpg', 'rb') as stream:
    container = stream.read()  # 读取文件内容

    with open(r'c:\p2\girl.jpg', 'wb') as wstream:
        wstream.write(container)

print('文件复制完成!')

内置函数 os

'''
os.path:
os.path.dirname(__file__)获取当前文件所在的文件目录(绝对路径)
os.path.join(path,'')  返回的是一个拼接后的新的路径
'''
import os
print(os.path) #<module 'ntpath' from 'D:\\Software Install\\Python_3.6.5\\lib\\ntpath.py'>
path = os.path.dirname(__file__)  # 获取当前文件所在的文件目录(绝对路径)
print(path) #E:/Python Script
print(type(path)) #<class 'str'>
result = os.path.join(path, 'openstack_landscape.jpg')
print(result) #E:/Python Script\openstack_landscape.jpg
# p1\girl.jpg ---->保存在当前文件所在的目录

with open(r'C:\CA\openstack_landscape.jpg', 'rb') as stream:
    container = stream.read()  # 读取文件内容
    print(stream.name)
    file = stream.name
    print('filename:',file) #filename: C:\CA\openstack_landscape.jpg
    filename = file[file.rfind('\\')+1:]  # 截取文件名
    print('Cut :',filename) #Cut : openstack_landscape.jpg

    path = os.path.dirname(__file__)
    print('path:',path) #path: E:/Python Script

    path1 = os.path.join(path, filename)
    print('path1:',path1) #path1: E:/Python Script\openstack_landscape.jpg
    
    with open(path1, 'wb') as wstream:
        result = wstream.write(container)
        print('reslut:',result)

 

posted @ 2023-10-08 16:53  しみずよしだ  阅读(18)  评论(0)    收藏  举报