文件对象:
open内建函数:通过了初始化输入、输出(I/O)操作的通用接口,成功打开文件后会返回一个文件对象,否则引发错误。file_object=open(file_name,mode=‘r’):file_name:表示我们要打开文件的路径;mode以什么样的方式打开文件。
close函数关闭文件
文件对象访问模式:
r(read):以读方式打开(文件不存在则报错)
w(write):以写方式打开(文件存在则清空,不存在则创建,覆盖写)
a(append):以追加模式打开(必要时创建新文件)
b(byte):以二进制模式打开(配合rb、wb操作)
文件输入:
文件指针:文件指针标记从那个位置开始读取数据,第一次打开文件时,通常文件指针会指向文件的开始位置,当执行了read方法后,文件指针会移动到读取内容的末尾。重新打开文件时,文件指针会重新指向文件的最开始位置。



readline按照行数读取文件内容


readlines把文件的所有的内容按行读取出来,放在列表中


当文件比较大时使用read读取就会把读取的内容放在内存中,内存有可能读取不下负载严重,此时使用readline一行一行的读取到内存中
读取大文件姿势,使用readline不知道具体执行几次,此时就需要循环


文件输出:
write()内建方法功能与read()和readline()相反,它把含有文本数据或二进制数据块的字符串写入到文件中,写入文件时,不会自动添加行结束标志,需要程序员手工输入(\n)。


writelines:和readlines一样,writelines()方法是针对列表的操作,它接受一个字符串列表作为参数,将它们写入文件,行结束符并不会被自动加入,如果需要必须在调用writelines()前给每行结尾加上结束符。


练习:模拟cp操作
创建cp.py文件,将/usr/bin/ls拷贝到/tmp/myls目录下,不要修改原始文件
/usr/bin/ls是二进制文件,所以需要使用rb、wb


with子句:用来简化代码,在将打开文件的操作放在with语句中,代码块结束后,文件将自动关闭。


函数:对程序逻辑进行结构化或过程化的一种编程方法。把具有独立功能的代码快组织为一个小模块,在需要的时候调用。函数的使用包含两个步骤:定义函数:封装独立的功能。调用函数:享受封装的成果
创建函数:使用def语句来创建,标题行由def关键字,函数的名字,以及参数的集合(可有可没有)组成,def子句的剩余部分包括了一个虽然可选但是强烈推荐的文档字串,和必须的函数体。
def function(形式参数):
代码块
调用函数:同大多数语言相同,Python用一对圆括号调用函数,如果没有加圆括号,只是对函数的引用。
函数的返回值:多数情况下,函数并不直接输出数据,而是向调用者返回值,函数的返回值使用return关键字,没有return函数默认返回None。
函数参数:----形式参数:函数定义时,紧跟在函数名后(圆括号内)的参数被称为形式参数,简称形参,由于它不是实际存在的变量,所以又称虚拟变量。---实际参数:在主调函数中调用一个函数时,函数名后面的圆括号中的参数称为‘实际参数’,简称实参。
定义一个函数get_sum计算两个数的和


当参数传递少一个参数时就会报错


默认参数:声明了默认值的参数,不向该参数传入值也是允许的,没有手动给形参赋值就使用默认值。当有实际参数默认参数就失效了


当给形式参数添加默认值时,有默认值的参数必须放到没有默认值参数的后面

位置参数:使用sys模块的argv列表接受。要在终端中执行


修改cp的程序,将源文件和目标文件通过参数进行传递


函数的返回值:多数情况下,函数并不直接输出数据,而是向调用者返回值。函数的返回值使用return关键字,没有return的话函数默认返回None。


练习:斐波那契函数


模块:模块是从逻辑上组织Python代码的形式,当代码量变得相当大的时候,最好把代码分成一些有组织的代码段,前提是保证它们的彼此互交,这些代码片段相互间有一定的联系,可能是一个包含数据成员和方法的类,也可能是一组相关但彼此独立的操作函数,一个.py文件就是一个Python模块。
导入模块(import):使用import导入模块,模块属性通过‘模块名.属性(变量)’的方式调用,模块函数通过‘模块名.函数名’的方式调用。导入模块时该模块的代码会被执行一次

模块加载:一个模块只被加载一次,无论导入多少次,如果两个文件相互导入防止了无限的相互加载,模块加载时,顶层的代码会自动执行
模块导入的特性:模块具有一个__name__特殊属性,当模块文件直接执行时,__name__的值为'__main__',当模块被另一个文件导入时,__name__的值就是该模块的名字


当__name__ == '__main__'时执行自己的函数

练习:编写一个能够生成8位随机密码的程序
使用random中的choice随机选择字母数字,改善程序用户可以自己决定生成多少位的密码
string模块中的string.digits和string.ascii_letters能够提供数字和字母



time模块:
时间的表达方式:时间戳timestamp:表示的是从1970年1月1日00:00开始按秒计算的偏移量。UTC (Coordinated Universal Time,世界协调时):即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。结构化时间(struct_time):由9个元素组成。
time.time模块:返回当前的时间戳
time.sleep模块:线程推迟指定的时间运行,单位为妙。


time.localtime(secs):将一个时间戳转换为当前时区的结构化时间。
time.gmtime(secs):和localtime方法类似,gmtime是将一个时间戳转换为UTC时区(0时区)的结构化时间。


可以使用数组下标、切片和具体名称的方式来获取具体的结构化时间


localtime的hour会增加8小时


time.mktime模块:将一个结构化时间转换为时间戳


time.strftime模块:将结构化时间转换为时间字符串


time.strptime模块:将时间字符串转换为结构化时间


结构化时间可以比较,越靠后的时间越大。
练习:取出指定时间段的日志
有一个日志文件,按时间先后顺序记录日志,给定时间范围(如9:00到12:00)取出该范围内的日志,自定义日志文件myweb,log




链式赋值、多元赋值、交换变量


keyword模块:查询关键字

查看内建模块,选中print函数,按Ctrl鼠标点击。该builtins.py会在Python环境启动时自动导入该模块

字符串:
字符串的拼接


字符函数

