文件
文本文件 使用文本编译器
打开文件 读文件 写文件 关闭文件
修改==覆盖
打开 open 关闭 close 读写 read write
open
区分大小写 打开方式 返回文件对象 不存在就报错
打开方式
r 默认 只读
w有则覆盖 无新建 只读
a末尾追加 无新建 追加
r+ 读写
w+
a+同上
r+b
w+b
a+b 可读可写
1. 打开 - 文件名需要注意大小写 file = open("README") 2. 读取 text = file.read() print(text) 3. 关闭 file.close()
read
一次性读入并返回文件内容 readline 逐行读取
file1 = open("README.txt") i = 1 while True: text1 = file1.readline().strip() if text1: print("这是第%s行内容" % i) i += 1 print(text1) else: break file2 = open("README.txt") # 通过for遍历按行读取文件所有内容 for i in file2.readlines(): print(i.strip()) file2.close()
with
自动关闭文件
with open("README.txt") as file1: while True: text1 = file1.readline().strip() if text1: print("这是第%s行内容" % i) i += 1 print(text1) else: break
文件的修改
1 将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)
2 硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件
函数的参数
位置参数
def maxnumber(x,y): the_max = x if x > y else y return the_max ret = maxnumber(10,20) print(ret)
关键字参数
def maxnumber(x,y): the_max = x if x > y else y return the_max ret = maxnumber(y = 10,x = 20) print(ret)
混合参数
def maxnumber(x,y): the_max = x if x > y else y return the_max ret = maxnumber(10,y = 20) print(ret)
默认参数
def demo(a,l = []): l.append(a) print(l) demo('abc') demo('123')
动态参数
def demo(*args,**kwargs):
*args 是元组 出去键值都参数
kwargs 是接受键值对的参数 保存在字典中
命名空间
-
全局命名空间 变量名与值的关系”的空间
-
局部命名空间 函数的运行中开辟的临时的空间
-
内置命名空间
顺序
-
在局部调用:局部命名空间->全局命名空间->内置命名空间
-
在全局调用:全局命名空间->内置命名空间
global
不可变 声明一个全局变量,在局部作用域中用全局变量的修改用global(字符串和数字)
列表 li = [] 字典 dic = { " ": , } 可以变 不用golbal
local
函数、循环或类等其他封闭结构内的变量。
nonlocal
-
不能修改全局变量。
-
在局部作用域中,对父级作用域(或者更外层作用域非全局作用域)的变量进行引用和修改,并且引用的哪层,从那层及以下此变量全部发生改变。