网站建设 意见征集教育培训机构前十名
文章目录
- 1、文件
- 1.1、with关键字
- 1.2、逐行读取
- 1.3、写入模式
- 1.4、多行写入
- 2、异常
- 2.1、try-except-else
- 2.2、pass
1、文件
1.1、with关键字
with关键字用于自动管理资源
使用with可以让python在合适的时候释放资源
python会将文本解读为字符串
# -*- encoding:utf-8 -*-
# 如果中文运行不了加上上面那个注释# 使用with后不需要调用close去关闭文件
# ./表示在当前目录
# 使用.\\也表示当前目录,第一个\表示转义
# with open('./text.txt') as file_obj:
# with open('.\\text.txt') as file_obj:
with open('text.txt') as file_obj:print(file_obj)msg = file_obj.read()
print(msg)
1.2、逐行读取
无论哪种方式都会改变 file_obj
所以后面那个什么也没读到
with open('text.txt') as file_obj:# 方式1lines = file_obj.readlines()print(lines)# 方式2for line in file_obj:# strip()用于去除空行print(line.strip())
1.3、写入模式
python只会将字符串写入文件中
若要写入数字,需将数字转化成字符串
def print_file(filename):with open(filename, 'r') as file_r:for info in file_r:print(info)def write_file(filename, mode, text):with open(filename, mode) as file_w:file_w.write(text)file_name = 'text.txt'
write_file(file_name, 'w', 'abcdef')
print_file(file_name)
write_file(file_name, 'w', '123')
print_file(file_name)
open的第二个实参mode:
- r 只读
- w 只写
文件不存在:创建新文件
文件存在:删除文件原有内容,再写入
可以理解为就是创建一个新文件
- a 只写
以追加的方式写入到末尾
- r+ 可读可写
其他的就不一一赘述了
1.4、多行写入
filename = 'text.txt'
with open(filename, 'w') as file_w:file_w.write(str(123))file_w.write(str(456) + '\n')file_w.write(str(789))with open(filename, 'r') as file_r:for info in file_r:print(info, end='')
2、异常
产生异常后,python会创建一个异常对象,如果编写了处理该异常的代码,程序将继续运行
2.1、try-except-else
当将0作为除数时,会产生以下错误
用try-except包裹后:
try:ret = 9 / 0
except ZeroDivisionError:print("0不能作为除数")
else:print(ret)
如果try中的内容运行没问题,python将会跳过except,执行else中的代码,并继续运行后面的内容,否则寻找对应的except并运行其中的代码,然后再执行后面的内容。一个try可对应多个except
2.2、pass
当捕获到异常但不想处理时,可用pass
try:ret = 9 / 0
except ZeroDivisionError:pass
else:print(ret)
笔记来源:《Python编程 从入门到实践》