读文件
1.一次读取全部文件
def readfile1(filename):
with open(filename) as fileobject:
contents=fileobject.read()
print(type(fileobject))
print(type(contents))
return contents
contents=readfile1('./pi.txt')
print(contents)
在读取文件前,先要用open函数打开文件,open函数的参数是文件路径,返回值的类型为_io.TextIOWrapper(可理解为文件对象),命名为fileobject
文件对象不能直接输出文件内容,需要调用文件对象的read函数,read函数的返回值是字符串
正常打开文件完后,还需要调用close函数关闭文件,以防止文件数据被破坏,但是,如果程序出现异常,可能导致close函数无法执行。所以,使用with关键字可以让通过系统来自动关闭文件,不用程序员操心
2.逐行读取文件
def readfile2(filename):
with open(filename) as fileobject:
print(type(fileobject))
for line in fileobject:
print(line)
print(type(line))
readfile2('./pi.txt')
当对文件对象进行遍历时,循环变量的类型是个字符串,所以可以逐行打印
可是,打印结果含有空行,和源文件内容不一致,因为文件每行尾都有换行符,加上print的换行符,一共两个,所以出现空行,
所以,需要用rstrip函数去除每行尾部的换行符,修改后,代码如下
def readfile2(filename):
with open(filename) as fileobject:
print(type(fileobject))
for line in fileobject:
print(line.rstrip())
print(type(line))
# contents=readfile1('./pi.txt')
# print(contents)
readfile2('./pi.txt')
逐行读取除了用上述方式外,还可以readlines函数读取文件,readlines函数的返回值是一个列表,存储的是每行文件的数据
def readfile3(filename):
with open(filename) as fileobject:
lines=fileobject.readlines()
print(type(lines),lines)
return lines
for line in readfile3('./pi.txt'):
print(line.rstrip())
文件对象的readlines函数的返回值是一个列表,文件按行将数据存储到该列表中
写文件
写入文件的方式有三种
第一种是指定open的第二个参数为'w',用这种方式向文件中写入内容时,会先将原来文件的内容清空,然后再写入内容
第二种是指定open的第二个参数为'a',用这种方式向文件中写入内容时,会将文件的内容直接追加至文件尾部
第三种是指定open的第二个参数为'r+',用这种方式向文件中写入内容时,直接从头开始写入,并将源文件中对应内容长度的数据替换
def writetofile(filename, contents, mode='a'):
if mode=='w':
print('clear origin file and then write')
with open(filename, mode) as fileobject:
fileobject.write(str(contents))
elif mode=='a':
print('just append contents to file')
with open(filename, mode) as fileobject:
fileobject.write(str(contents))
elif mode=='r+':
print('r+')
with open(filename, mode) as fileobject:
fileobject.write(str(contents))
contents=1233445567889
writetofile('./2pi.txt', contents)
使用默认参数'a'时,直接将1233445567889转换为字符串,然后追加字符串至文件尾部
当把最后一行的函数的第三个参数指定为'w'时,结果如下
使用默认参数'w'时,直接将1233445567889转换为字符串,然后清空文件,将字符串写入文件
当第三个参数为'r+'时,结果如下
只是将文件中写入数据长度的内容替换掉,其余不变
捕获异常
如果不捕获异常,异常会使程序终止,捕获异常后,进行相应的处理(也可以不处理),使程序更加健壮,对用户更友好
比如执行5/0,就会抛出异常,使程序终止执行
在Python中,使用try-except语句捕获异常
try:
print(5/0)
except ZeroDivisionError as e:
print('you cant divide by 0')
此时没有弹出错误信息,只是打印一个友好的提醒
使用try-except-else完善异常处理
在实际的处理异常过程中,更常用的方法是将将可能发生异常的代码加入到try下,如果try执行成功,执行else,except依然执行异常处理
def dividefunc():
while True:
try:
a=int(input('input one num'))#可能出现异常的代码
b=int(input('input another nums'))
except ValueError:#捕获异常
print('a and b must be number')#提示
else:
try:
print(a/b)#可能出现异常的代码
except ZeroDivisionError as e:
print('you cant divide by 0')
dividefunc()
上述代码的执行过程如下,先尝试将输入转换为字符串,
如果转换失败,捕获异常,打印语句,重新输入,
如果转换成功,执行else的代码,在else代码中,再次捕获除0异常,如果b非0,打印结果,否则捕获异常并提示,然后重新输入
上述代码也表明,异常处理可以嵌套
参考:
《Python编程从入门到实践》
欢迎大家评论交流,作者水平有限,如有错误,欢迎指出