第10章 文件和异常

with open('C:/Users/lenovo/Desktop/pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())

with open('C:/Users/lenovo/Desktop/pi_digits.txt') as file_object:
for line in file_object:#逐行读取
print(line.rstrip())

创建一个包含文件中各行内容的列表

with open('C:/Users/lenovo/Desktop/pi_digits.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())

写入文件
with open('C:/Users/lenovo/Desktop/pi_digits.txt', 'w') as file_object:
'w'为写入模式,'r'为读取模式,'a'为附加模式,'r+'为读取写入模式,
file_object.write("I love programming.")

异常
除零异常

print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)

输出
Give me two numbers, and I'll divide them.
Enter 'q' to quit.

First number: 5
Second number: 0
You can't divide by zero!

First number: 5
Second number: 2
2.5

First number: q

读入错误

try:
with open('C:/Users/lenovo/Desktop/alice.txt') as file_object:
lines = file_object.readlines()
except FileNotFoundError:
print("Sorry, this file does not exist.")

pass占位符,表示在程序的某个地方什么也没有做

存储数据
json.dump()和json.load()

import json
numbers = [2, 3 , 5 , 7 , 11, 13]
filename = 'C:/Users/lenovo/Desktop/number.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
with open(filename) as f_obj:
numbers_2 = json.load(f_obj)
print(numbers_2)

重构
将代码划分为一系列完成具体工作的函数
重构使代码更清晰,更易于理解

你可能感兴趣的:(第10章 文件和异常)