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)
无论哪种方式都会改变 file_obj
所以后面那个什么也没读到
with open('text.txt') as file_obj:# 方式1lines = file_obj.readlines()print(lines)# 方式2for line in file_obj:# strip()用于去除空行print(line.strip())
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:
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='')
产生异常后,python会创建一个异常对象,如果编写了处理该异常的代码,程序将继续运行
当将0作为除数时,会产生以下错误
用try-except包裹后:
try:ret = 9 / 0
except ZeroDivisionError:print("0不能作为除数")
else:print(ret)
如果try中的内容运行没问题,python将会跳过except,执行else中的代码,并继续运行后面的内容,否则寻找对应的except并运行其中的代码,然后再执行后面的内容。一个try可对应多个except
当捕获到异常但不想处理时,可用pass
try:ret = 9 / 0
except ZeroDivisionError:pass
else:print(ret)
笔记来源:《Python编程 从入门到实践》