目录
-
文件读写
file = open('a.txt','w')
file.write('haha')
file.close()
file = open('a.txt','r')
content = file.read()
print(content)
file.close()
open函数创建一个文件对象并将其与磁盘文件关联,第一个参数是文件路径,第二个参数是模式,包括读、写、追加等等,基本和其他语言类似。
文件对象支持用read、readline和write等方法对文件进行读写。用完记住用close方法关闭文件。
-
判断文件结尾
file = open('haha.txt', 'w')
file.write('line1\n')
file.write('line2\n')
file.write('line3\n')
file.close()
file = open('haha.txt', 'r')
line = file.readline()
while line != '' :
print(line)
line = file.readline()
file.close()
file = open('haha.txt', 'r')
for line in file:
print(line)
file.close()
readline方法在到达文件末尾时会返回空字符,可以用它作为判断条件。
或者使用for循环会更优雅。
注意,上面打印会多打一个空行,可以使用字符串line的rstrip('\n')方法去掉末尾空行,或者print函数加参数end='',来指示结尾不用加空行。
-
异常
-
使用 try/except 捕获异常
try:
x = 1 / 0
except ZeroDivisionError:
print("ZeroDivisionEror")
-
支持多个except子句
try:
x = int("1 / 0")
except ValueError:
print("ValueError")
except ZeroDivisionError:
print("ZeroDivisionEror")
支持多个except子句,分别捕获多个异常
-
except不指定异常类型
try:
x = 1 / 0
except :
print("ERROR!")
except不指定异常类型,可以捕获所有异常
-
将异常赋给变量
try:
x = 1 / 0
except Exception as e:
print(f"GOT ERROR: {e}")
可以将异常赋给变量以便输出错误信息,如上面的e。
此时一定要指定异常类型,如果不知道异常类型,就用Exception类型。
-
else子句
try:
x=int(input("input a integer"))
except:
print("ERROR: wrong input")
else:
print(f"your number is {x}")
try/except/else:在所有except子句后可以出现else子句,当try语句没有引发异常时才会执行。
-
finally子句
try:
file = open('notfound.txt','r')
for line in file:
print(line)
except:
print("open file error!")
finally:
file.close()
try/except/finally:不管有没有抛出异常,都会执行,用于释放资源等场景。
注:上面写法有问题,如果打开文件时抛异常,则在finally中file变量都不存在。
上一篇:python基础02——函数