南京林业大学实验与建设网站,免费网站制作网站源码,合肥市庐阳区住房和城乡建设局网站,建设一站式服务网站文章目录1、文件1.1、with关键字1.2、逐行读取1.3、写入模式1.4、多行写入2、异常2.1、try-except-else2.2、pass1、文件 
1.1、with关键字 
with关键字用于自动管理资源 使用with可以让python在合适的时候释放资源 python会将文本解读为字符串 
# -*- encoding:utf-8 -*-
# 如…
文章目录1、文件1.1、with关键字1.2、逐行读取1.3、写入模式1.4、多行写入2、异常2.1、try-except-else2.2、pass1、文件 
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编程 从入门到实践》