#encoding:utf-8

#读取文件
'''关键字with在不再需要访问文件时将其关闭'''
with open('pi_digits.txt') as file_object:
    contents = file_object.read()   #read()把文件的全部内容读取成一个长长的字符串
    print(contents.rstrip())    #rstrip()的作用是删除字符串末尾的空白

#绝对文件路径读取文件
print("\n")
file_path = '/home/shihao/Desktop/python_work/pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.rstrip())

#逐行读取文件内容
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip())

#创建一个包含文件各行内容的列表
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    lines = file_object.readlines()  #readlines()从文件中读取每一行,并将其存放在一个列表中

for line in lines:
    print(line.rstrip())

#写入文件
file_name = 'programming.txt'
with open(file_name, 'w') as file_object:
    file_object.write("I love proggramming.\n")       #write()将一个字符串写入文件
    file_object.write("I am shihao\n")

#附加到文件
file_name = 'programming.txt'
with open(file_name, 'a') as file_object:
    file_object.write("I love you!")
#encoding:utf-8

#处理ZeroDivisionError
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

#处理FileNotFoundError
try:
    file_name = 'alice.txt'
    with open(file_name) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    print("The file " + file_name + " not found")
#encoding:utf-8

#使用json.dump()来存储数据列表
import json
numbers = [2, 3, 5, 7, 11, 13]
file_name = 'numbers.json'
with open(file_name, 'w') as f_obj:
    json.dump(numbers, f_obj)

#使用json.load()读取列表到内存中
with open(file_name) as f_obj:
    numbers = json.load(f_obj)
print(numbers)