8.1 读取文件

Code
f = open("data/pi_digits.txt",mode="r")
contents = f.read()
print(contents)
contents = contents.rstrip()
print(contents)
f.close()
3.1415926535
  8979323846
  2643383279




3.1415926535
  8979323846
  2643383279
Code
with open("data/pi_digits.txt",mode="r") as g:
    for i in g:
        print(i)
3.1415926535

  8979323846

  2643383279






Code
from pathlib import Path
path = Path("data/pi_digits.txt")
f = path.read_text()
f = f.splitlines()
for i in f:
    print(i)
3.1415926535
  8979323846
  2643383279


8.2 写入文件

Code
with open("data/write.txt",mode="a") as w:
    w.write("Π是无限不循环小数。")
with open("data/write.txt",mode="a") as w:
    w.write("fafhaofhaohfo")

8.3 异常处理

exception

Code
def division(dividend,divisor):
    answer = dividend/divisor
    return(answer)
division(4,2)
division(4,0)

def division_(dividend,divisor):
    try:
        answer = dividend/divisor
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        return(answer)
    finally:
        print("OK")
division_(4,2)
division_(4,0)
ZeroDivisionError: division by zero

8.4 存储数据