Python基础学习
比如写 默认是内存的缓存满了在往内存里写
buffer 内存中的临时文件
import syssys.stdout.write() #std 标准 f.truncate() 截断
- 不写是清空文件
- f.truncate(10) 从文件开头截断到 指定位置 移动也不好使 都是从头开始
r+ 读写 -- 常用
w+ 写读 ---- 没啥用
a+ 追加读
rb 二进制读文件 比如视频等 二进制 不传 encoding
- 网络传输 3.0 socket 传输
- 二进制文件打开
wb 二进制写 2.0 区分不大 3.0 要注意
打开一个文件 修改完存到另一个文件
- vim 是把文件全部放内存中 今行操作
- 文件修改: 从一个文件里读 写到另一个文件 as f
with 自动关闭文件
- 2.7 后支持 多个文件
- with open('a.txt','r'), open('b.txt','r') as f1,f2:
- with open("/Users/qiao/changhenge.txt",'r',encoding='utf-8') as f,\
- open("/Users/qiao/changhehge_new.txt",'w') as f2:
#high 逼格 高效 读一行 删一行内存 : file 变成了迭代器 不是列表了
for line in file:
print (line)
字符编码# utf-8 --decode---> unicode ---encode-->gbk# utf-8 <--encode-- unicode <---decode---gbk
- >>> sys.getdefaultencoding()
- 'ascii'
- 英文 按 accii
- 中文三个字节 ?
- Unicode 中文英文都占两个字节 万国编码
- ascii 一个字节
- utf-8 可变长
- gbk
- Python3 默认编码 Unicode
- 2.7 默认编码 accii
- s =
- print (s.encode("gbk"))
- print (s.encode("utf-8"))
- print (s.encode("utf-8").decode("utf-8"))
- print (s.encode("utf-8").decode("utf-8").encode("gbk"))
函数
- 不加 return 默认返回 null
- Python 可以返回多个值
- 形参
- 实参 实际存在 占用空间的
- def test(x,y):
- test(1,2) 与形参一一对应
- test(y=2,x=1) 关键词调用 与形参顺序无关
- def test(x,y,z)
- test(1,z=3,y=2) 正确
- test(1,2,y=3) 错误
- def test(x,y=2)
- 调用的时候 可以 test(1) 默认参数非必传
- 用处:a 连接数据库 b 默认值
参数组 :可以传不固定参数 def test(*args):*args 接收的是 位置参数 不能接收 关键字参数 转换成元组 形式位置参数不能写在 关键字参数 后面 def test(x,*args):
print(x)
print(args) 调用 test1(1,2,3,4,5,6,7)
def test2(**kwargs) 形参是字典
- def test4(name,age=18,**kwargs):
- test2(name='alex',age=8,sex='F')
- 关键字参数
- **kwargs 功能 把关键字参数转换成字典
- 位置参数 关键字参数
- def test3(name.**kwargs) test3('alax',age=8)
- 参数组要往后放
局部变量 在函数里变全局变量 global name 但不要这样做 尽量不要这样做全局变量 在外部显示字符串 和 整数 是不可以在局部里改全局 list 集合 字典 类等稍复杂的数据对象 可以最大递归次数 999 递归 特性:
- 函数调用是 通过栈(先进后出 )
- 必须有一个明确的结束条件
- 每次进入更深一层的递归 问题规模应比上次减少
- 递归层过多 会导致栈溢出
函数式编程 : 通过一堆函数调用 实现功能 Python 不适用
- hashshell erlang lisp
- 例如 subtract(multiply(add(1,2),3),4)
高阶函数: 一个函数接受另一个函数作为参数
来源: