- 2020年11月28总结
- 拼接目录 new_path = os.path.join(os.getcwd(), “test”)
print(new_path)
# 拼接文件 new_path = os.path.join(os.getcwd(), “test.txt”)
print(new_path)
# 拼接多重目录 new_path = os.path.join(os.getcwd(), “test/test/test”)
print(new_path)
# 拼接多个目录、文件 new_path = os.path.join(os.getcwd(), “test”, “Test”, “ok.txt”)
print(new_path)
2020年11月28总结
2020年11月28总结
# 参数的例子
#不定长参数
def function_a(normal,args):
print(normal)
for i *in args:
print(i)
function_a(“name”,“age”,“tele”)
#关键字参数
def function_key_value(kwargs):
print(kwargs)
for key,value in kwargs.items():
print(key+“=”**+str(value))
function_key_value(name=“小明”)
#如果传入是字典
dic = {‘abc’: 123, ‘aaa’: 333, ‘wer’: 334}
function_key_value(**dic)
#可迭代对象不一定是迭代器
str = “name”
#对字符串试试迭代操作
str_iter = iter(str)
print(next(str_iter))
for i in str:
print(i)
# Map会将一个函数映射到一个输入列表的所有元素上。这是它的规范:
def multiply(x):
return (x * x)
def add(x):
return (x + x)
funcs = [multiply, add]
for i in range(3):
value = map(lambda x: x(i), funcs)
print(list(value))
# filter
number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
#可以去重
some_list = [‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘m’, ‘n’, ‘n’]
print(set(some_list))
#装饰器的用法
def a_new_decorator(a_func):
def wrapTheFunction():
print(“I am doing some boring work before executing a_func()”)
a_func()
print(“I am doing some boring work after executing a_func()”)
return wrapTheFunction
def a_function_requiring_decoration():
print(“I am the function which needs some decoration to remove my foul smell”)
a_function_requiring_decoration()
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
a_function_requiring_decoration()
#这正是python中装饰器做的事情
@anew_decorator
def a_function_requiring_decoration():
“””Hey you! Decorate me!”””_
print(“I am the function which needs some decoration to remove my foul smell”)
# a_function_requiring_decoration()
print(afunctionrequiring_decoration.__name)
from functools import wraps
def logit(func):
@wraps(func)
def withlogging(args, *kwargs):
print(func._name + “ was called”)
return func(args, kwargs)
return* with_logging
@logit
def additionfunc(x):
“””Do some math.”””_
return x + x
print(addition_func(13))
格式化输出字符串,format(value, formatspec)实质上是调用了value的_format(format_spec)方法。
In [104]: print(“i am {0},age{1}”.format(“tom”,18))
i am tom,age18
复制代码
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
18 {:>10d} ‘ 18’ 右对齐 (默认, 宽度为10)
18 {:<10d} **'18 '** 左对齐 (宽度为10)
18 {:^10d} ‘ 18 ‘ 中间对齐 (宽度为10)
# 路径问题
import os
myFiles = [‘accounts.txt’, ‘details.csv’, ‘invite.docx’]
for filename in myFiles:
print(os.path.join(‘C:\demo\exercise’, filename))
path = os.path.abspath(“.”)
path1 = os.path.join(path,‘11’)
print(path1)
获取路径的方法
import os
# 当前文件的绝对路径
current = os.path.abspath(file)
# 当前文件的父级目录
BASEDIR = os.path.dirname(current) # 以上两行代码也可以使用 _BASE_DIR = os.getcwd()代替
# 定义config目录路径 — os.sep是分隔符
_conf_file = BASE_DIR + os.sep + “config.yaml”
# 定义一个方法返回yaml文件的路径
def get_config_file():
return _conf_file
print(get_config_file())
os.path.split(path)
分离文件名和扩展名
# 目录 os.path.split(os.getcwd())
# 文件 os.path.split(os.path.realpath(file))
os.path.join()用于路径的拼接
拼接目录 new_path = os.path.join(os.getcwd(), “test”)
print(new_path)
# 拼接文件 new_path = os.path.join(os.getcwd(), “test.txt”)
print(new_path)
# 拼接多重目录 new_path = os.path.join(os.getcwd(), “test/test/test”)
print(new_path)
# 拼接多个目录、文件 new_path = os.path.join(os.getcwd(), “test”, “Test”, “ok.txt”)
print(new_path)
- BaseSettings 文件存放的就是项目通用的常量,譬如项目路径 projectpath = os.path.split(os.path.split(os.path.realpath(_file))[0])[0]
- 当我想获取 config 文件夹下的 config.ini 时,我的变量就是 configIni_path = os.path.join(project_path, “config”, “config.ini”) ,以此类推~
- 可以看到,其实还是蛮长一行代码的,并且需要由内而外的阅读代码;
- 无独有偶,接触到了 pathlib 库之后,发现原来它有这么好用,并且可以完全替代 os.path
from pathlib import Path
v = Path.cwd() #获取当前路径
vparent = Path.parent #获取上层目录_
van = v.parent.parent #获取上上层目录_
paths = [“test”,“test.txt”]
vjoin = Path.cwd().parent.joinpath(*paths) #拼接路径_
# 创建 project/test目录
Path(‘project/test’).mkdir(parents=True, exist_ok=True)
# 将test.txt 重命名为 test1.txt
Path(‘test.png’).rename(‘test1.png’)