Python学习
一、文件对象
1. 文件对象的读取
- 建立文件对象
open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。
open() 函数常用形式是接收两个参数:文件路径(相对或者绝对路径)(file)和模式(mode)。
open(file, mode='r')
mode
r:以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb:以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
示例:
f = open("c:\\users\\chen\\test.txt",mode='r')
- 读取文件
read()方法:从文件读取指定的字节数,如果未给定或为负则读取所有。
seek()方法:移动文件读取指针到指定位置
seek(offset[, whence])
offset:开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。
whence:默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。
readline(): 方法用于从文件读取整行,如果指定了一个非负数的参数,则返回指定大小的字节数。
readlines() :方法用于读取所有行并返回列表。
- 关闭文件对象
close方法,关闭后的文件不能再进行读写操作。
2. 文件对象的写入
- 打开文件
open("文件路径",mode="wb")
- 写入文件内容
writelines() 方法用于向文件中写入一序列的字符串。如果文件打开模式带 b,那写入文件内容时,str (参数)要用 encode 方法转为 bytes 形式,否则报错:TypeError: a bytes-like object is required, not ‘str’。
writelines( [ str ])
示例:
f = open("c:\\users\\chen\\test.txt",'wb')
f.writelines([b"first line\r\n",b"second line\r\n",b"third line\r\n"])
f.close()
或者
f = open("c:\\users\\chen\\test.txt",'w')
f.writelines(["first line\n","second line\n","third line\n"])
f.close()
- 关闭文件对象
close方法,关闭后的文件不能再进行读写操作。
3. 复制文件
利用while True
rf = open("被复制的文件路径",'rb')
wf = open("复制到哪个路径",'wb')
while True:
data = rf.read(4096) # 一次读取4096字节,即4k
if date == b"": # 读取结束标识
break
wf.write()
rf.close()
wf.close()
二、函数
- 概述
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率,Python提供了许多内建函数,如print()… 自己创建函数叫做用户自定义函数。 - 语法格式
def 函数名(参数列表):
函数体
- 示例
示例一:
def hello():
print("hello,world")
# 调用函数
hello()
# 运行结果:hello,world
示例二:参数和返回值
def max(a, b): # a、b为形式参数
if a > b:
return a
else:
return b
a = 4
b = 5
print(max(a, b)) # a、b为实际参数
- 匿名函数
python 使用 lambda 来创建匿名函数。
语法格式:
lambda [arg1 [,arg2,.....argn]]:expression
示例:
sum = lambda arg1, arg2: arg1 + arg2
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
三、模块
-
将定义的方法和变量等这些定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。存放在Lib目录下。
-
自定义模块
自定义模块不能以数字开头,不能和默认的模块重名。
新建文件:hello.py
"""
这里写模块的注释:
1. 介绍模块的功能;
2. 包含哪些功能;
3. 作者等信息
"""
"""Hello module
This is my custom module to print hello
-------------
hello_01()
hello_02()
-------------
author_name:code_chen
"""
p_hello = "hello,world"
"hello role is to define a hello,world"
def hello_01():
"hello01 role"
return "hello's function hello01"
def hello_02():
"hello02 role"
return "hello's function hello02"
测试:和hello.py在同级目录下新建测试文件
import hello
print(help(hello))
print(dir(hello))
print(help(hello.hello_01))
print(hello.p_hello)
结果:
from…import:
从模块中导入一个指定的部分到当前命名空间中,如导入hello模块中的hello_01函数
from hello import hello_01
print(hello_01())
# 运行结果
hello's function hello01
四、错误和异常
1. 错误
Python的语法错误即解析时错误
示例:
while True
print('Hello world')
# SyntaxError: invalid syntax
代码错误,因为while True后面缺少了一个冒号,语法分析器指出了出错的一行,并且在最先找到的错误的位置标记了一个小小的箭头。
2. 异常
- 即便程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。
- 示例
>>> 10 * (1/0) # 0 不能作为除数,触发异常
ZeroDivisionError: division by zero
>>> 4 + spam*3 # spam 未定义,触发异常
NameError: name 'spam' is not defined
>>> '2' + 2 # int 不能与 str 相加,触发异常
TypeError: can only concatenate str (not "int") to str
- 处理异常
- try except
和Java中的try{…}catch{…}用法类似
try:
执行代码
except (错误类型1,错误类型2...):
发生异常时执行的代码
示例1:处理除数不能为0异常
def division(a,b):
num = a / b
return num
f_num = int(input("please input a num:"))
s_num = int(input("please input a num:"))
try:
result = division(f_num,s_num)
print(result)
except ZeroDivisionError:
print("Divisor cannot be zero")
运行结果:
示例2:用户中断的信息会引发一个 KeyboardInterrupt 异常(Ctrl+c);发现了一个不期望的文件尾,而这个文件尾通常是Ctrl+d引起的EOFError:
def division(a,b):
num = a / b
return num
try:
f_num = int(input("please input a num:"))
s_num = int(input("please input a num:"))
result = division(f_num,s_num)
print(result)
except ZeroDivisionError:
print("Divisor cannot be zero")
except (EOFError,KeyboardInterrupt):
pass