python学习日记之文件与异常

148 阅读1分钟

一.文件

1.全部读取

with open('D:\code02\pi.txt') as file_object:
    print(file_object.read())

2.逐行读取

with open('D:\code02\pi.txt') as file_object:
    for line in file_object:
    #去除空格
        print(line.rstrip())

3.覆盖写入

with open('D:\code02\pi.txt','w') as file_object:
    file_object.write("ni hao")

4.追加写入

with open('D:\code02\pi.txt','a') as file_object:
    file_object.write("ni hao")

异常

try:
    print(5/0)
except ZeroDivisionError:
    print("除数不能为0")