Python Leanring
注意: 函数和语句都用斜体标识出来了,加粗的字符表示重点强调。
Finally
为了确保一些代码在发生任何错误的时候都能够运行,你可以使用finally声明。finally声明被放在try/except声明的最底部。在finally声明内的代码总是在try代码块之后执行,也有可能在except代码块之后运行。
示例一:
try:
print("hello")
print(1/0)
except ZeroDivisionError:
print("Divided by zero")
finally:
print("This code will run no matter what")
Result:
>>>
Hello
Devided by zero
This code will run no matter what
>>>
示例二:
try:
print(1)
except:
print(2)
finally:
print(3)
Result:
>>>
1
3
>>>
示例三:
try:
print(1)
print(20/0)
print(2)
except ZeroDivisionError:
print(3)
finally:
print(4)
Result:
>>>
1
3
4
>>>
如果在之前的代码块中出现没有被捕获的exception,在finally声明内的代码依然可以执行。
try:
print(1)
print(10/0)
except ZeroDividedError:
print(unknown_var)
finally:
print("This is executed last")
Result:
>>>
1
This is executed last
ZeroDivisionError:division by zero
During handling of the above exception, another exception occurred:
NameError:name'unknown_var' is not defined
>>>
对上面的代码进行修改
try:
print(1)
print(10/0)
except ZeroDividedError:
print("unknown_var")#没有加引号的时候表示单独的变量,而这个变量必须提前定义,加了引号之后表示的是字符串。
finally:
print("This is executed last")
Result:
>>>
1
unknown_var
This is executed last
>>>
Raising Exceptions
你可以通过是用raise声明来引起异常。可以通过引起异常来限制程序的使用,例如,如果你预见这个代码会陷入一个循环,那么这将会是非常有用的。你也可以用来检查输入的文件是否有正确的行数或者列数,或者是否从正确的地方开始,如果不满足条件的话,就会引起异常。
print(1)
raise ValueError
print(2)
Result:
>>>
1
ValueError
>>>
try:
print(1/0)
except ZeroDivisionError:
raise ValueError
Result:
>>>
ZeroDivisionError:division by zero
ValueError
>>>
可以给raise指定具体的关于异常的信息来引起异常,例如:
name="123"
raise NameError("Invalid name!")
Result:
>>>
NameError:Invalid name!
>>>
num=input(":")
if float(num)<0:
raise ValueError("Negative")
在except代码块中,可以使用raise语句而不适用任何语句来重新引发异常,例如:
try:
num=5/0
except:
print("An error occurred")
raise
Result:
>>>
An error occurred
ZerroDivisionError division by zero
>>>
Assertions
声明是一个全局性的检测,你可以打开它或者当你已经完成对程序的检查的时候把它关掉。一个表达式是可以被进行检查的,并且如果结果出现错误,就会有异常产生。可以使用assert 语句来进行声明。
示例一:
print(1)
assert 2+2==4
print(2)
assert 1+1==3
print(3)
Result:
>>>
1
2
AssertionError
>>>
示例二:
print(0)
assert "h" != "w"
print(1)
assert False #会报错,下面的代码不会继续运行,
print(2)
assert True #不会报错,下面的代码可以继续运行
print(3)
>>>
0
1
AssertionError
>>>
assert 可以使用第二个语句,如果assert 声明失败了,第二个语句会被传递给引起的AssertionError。
示例一:
temp=-10
assert(temp>=0),“Colder than absolute zero!"
Result:
AssertionError:Colder than absolute zero!
! AssertionError异常可以像任何其他异常一样使用try-except 语句捕获和处理,但是如果不处理,这种类型的异常将会导致程序终止。
示例二:
def my_func(x):
assert x>0,"Error!"
print(x)
my_func(9) #不会出现异常
my_func(-1) #出现异常
Result:
>>>
9
>>>
AssertionError:Error
>>>
Open files
你可以使用Python 读取或者写入文件的内容。文本文件很容易被进行操作。在文件被编辑之前,它首先要被打开,打开文件可以使用函数open
myfile=open("filename.txt")
!open 函数的声明是文件的路径。如果文件是在当前程序的工作目录下,那么你就可以只指定文件的名字。
你可以通过使用open 函数胡的第二个声明来指定用来打开文件的模式 。
发送给"r" 意味着以读取模式打开,这是默认的打开文件的方式
发送给“w”意味着以读写的模式打开文件,可以重新改写文件的内容
发送给“a” 意味着以附方式打开文件,为的是在文件的最后添加新的内容
添加“b”意味着以二进制的模式打开文件,这可以用来打开非文本文件(例如图像和声音文件)
示例一:
# 读写模式
open("filename.txt","w")
#只读模式
open("filename.txt","r")
open("filename.txt")
#二进制读写模式
open("filename.txt","wb")
!你可以使用+ 在上面展示的每种模式的后面,为它们提供额外的获得文件的模式。例如,r+ 表示的是以读入和写入的模式打开文件;w+ 表示的是以写入和读入的方式访问文件;a+ 表示的是以附加和读取的模式访问文件。
一旦文件被打开而且被使用之后,你就可以关闭文件了,可以使用文件对象的close 来关闭文件。
示例二:
file=open("filename.txt","w")
# 对文件进行一些操作
file.close()#关闭存储在变量file中的文件内容
Reading Files
以文本模式打开的文件内容可是使用read 来读取。
示例一:
file=open("filename.txt","r")
cont=file.read()
print(cont)
file.close()
!这个代码将会输出整个"filename.txt"的内容
为了只读取文件中的特定内容,你可以提供一个数字作为read 函数的声明。这个数字决定了应该被读的字节数butes 。你可以使用更多的声明来访问同一个文件对象,从而逐一字节地读取文件的更多内容。没有声明的时候,read* 返回的是文件的剩下部分。
示例一:
file=open("filename.txt"."r")
print(file.read(16))
print(file.read(4))
print(file.read(4))
print(file())
file.close()
注意: 数值为负数的时候和没有参数一样,将会返回全部的内容,而且空格也算是一个字符串。
示例二:
file=open("filename.txt","r")
for i in range(21):#总共输出21次,每次输出4bt
print(file.read(4))
file.close()
文件中所有的内容将会被进行读取,任何试图尝试从文件中进一步读取的声明都将会返回空的字符串,因为实际上你试图从文件的结尾读取东西。
示例一:
file=open("filename.txt","r")
file.read()
print("re-reading")
print(file.read())#没有内容输出了,因为之前已经读完了
print("Finished")
file.close()
示例二:
file=open("filename.txt","r")
str=file.read()
print(len(str))
file.close()
为了检索文件中的每一行,你可以使用readlines方法来返回一个列表,这个列表中的每一个元素代表的是文件的每一行。
示例一:
file=open("filename.txt")
print(file.readlines())
file.close()
Result:
>>>
['Line 1 text \n','Line 2 text \n','Line 3 text \n']
>>>
你也可以使用for 循环来迭代读取文件中的行:
示例二:
file=open("filename.txt","r")
for line in file:
print(line)
file.close()
Result:
>>>
Line 1 text
line 2 text
line 3 text
>>>
! 在输出中,行与行之间是通过空白行来进行分开的,因为print 函数会自动添加新行到文件输出的最末端,但是使用readlines 函数读出来的文件的行有点怪怪的。
示例二:
len(open("test.txt"),readlines())#返回文件的行数
Writing Files
为了写入文件可以使用write 方法,它能够将一个字符串写到文件中:
例如:
file=open("newfile.txt","w)
file.write("This has been written to a file\nIt has some context")#如果要添加多行内容,需要在每行内容的结尾加换行符“\n".
file.write("I want to add more lines")#可以重新添加
file.close()
file=open("newfile.txt","r")
print(file.read())
file.close()
Result:
>>>
This has been written to a file
>>>
! "w"模式将创建一个文件,如果之前这个文件不存在的话
示例二:
file=open("newfile.txt","w")
for i in range(20):
file.write("I want an apple\n")#如果希望每次加入的内容单独成行的话就需要在加入的内容的结尾加上换行符。
file.close()
file=open("newfile.txt","w")
for line in file:
print(line)
file.close()
当一个文件被以写入(write) 模式打开的时候,文件现存的内容将会被删除。
示例一:
file=open("newfile.txt","r")
print("reading initial contents")
print(file.read())
print("Finished")
file.close()
file=open("newfile.txt","w")
file.write("some new text")
file.close()
file=open("newfile.txt","r")
print("reading new contents")
print(file.read())
print("Finished")
file.close()
Result:
>>>
reading initial contents
some initial text
Finished
Reading New contents
some new text
Finished
>>>
!文件中的内容已经被覆盖掉了,所以如果你以"w"模式打开一个文件然后立刻将文件关闭,那么里面的内容将会被删除掉
write 模式可以返回被写入到文件中的字节数,如果这些内容被成功写入到文件中的话:
mag="Hello world!"
file=open("newfile.txt","w")
amount_written=file.write(mag)
print(amount_written)
file.close()
Result:
>>>
12
>>>
如果想写入一些非字符创的内容,就需要先将其转变为字符串
#如果字符串的内容被成功写入到文件中,那么
file.write(mag)==len(mag)
Working with files
确保文件在被使用之后是被关闭的,有助于避免内存资源的浪费。其中一个避免发生这样的事情的方法就是使用use 和finally 函数。
示例一:
try:
f=open("filename.txt")
print(f.read())
finally:
f.close()
!这样做可以确保文件总是关闭的,即使有错误发生
示例二:
try:
f=open("filename.txt")
print(f.read())
print(1/0)
finally:
f.close()
另外一种实现这个步骤的方式就是使用with 语句。with 语句创建了一个临时的变量,通常叫做f,这个变量仅能在with 语句的缩进块中被进行访问。
示例一:
with open("filename.txt") as f:
print(f.read())
在with 声明的末尾处,这个文件将会被自动关闭,即使有异常伴随着发生。
示例二:
file=open("test.txt","w")
file.write("This is an add context")
file.close()
try:
with open("test.txt") as f:
print(f.read())
except:
print("Error")
Result:
>>>
This is an add context
>>>
示例三:
try:
print(1)
assert 2+2==5
except AssertionError:
print(3)
except:
print(4)
示例四:
try:
print(1)
assert 2+2==5
except AssertionError:
print(3)
except:
print(4)
Result:
>>>
1
3
>>>