"""
第10章 文件和异常
xx.read()
xx.readlines()
ZeroDivisionError 异常
FileNotFoundError异常
try-except 代码块
pass
"""
"""
新建pi_digits.txt
3.1415926535
8979323846
2643383279
保存至此py同文件夹
"""
with open('pi_digits.txt') as file_object:
"""函数open接受一个参数:文件名,返回一个表示文件的对象"""
contents = file_object.read()
print(contents)
"""
输出结果很有可能多出一个空行
read到达文件末尾时返回一个空字符串,显示出来就是一个空行
要删除末尾行,可使用rstrip(),即:
print(contents.rstrip())
"""
"""
这里使用了 open() 但未使用 close()
若都使用,如果程序存在bug,导致close()未执行,文件将不会关闭,可能导致文件丢失或受损。
如果过早调用close(),可能使用时已关闭,会导致更多错误。
因而只管打开文件,Python能根据前面的结构,在需要时使用它,在合适的时候自动将其关闭
"""
with open('file_testing\pi.txt') as file_object2:
contents = file_object2.read()
print(contents)
file_path = 'D:\AppStore\matlab2018a\pi.txt'
with open(file_path) as file_object3:
contents = file_object3.read()
print(contents)
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
"""
逐行读取每一行结束都会有一个空行
因为文件中每行末尾都有一个看不见的换行符
而print语句也会加上一个换行符,因此有两个
消除空行依旧使用:
print(line.rstrip())
"""
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
"""
['3.1415926535\n', ' 8979323846\n', ' 2643383279']
"""
for line in lines:
print(line.rstrip())
"""
3.1415926535
8979323846
2643383279
"""
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
pi_string2 = ''
for line in lines:
pi_string += line.rstrip()
pi_string2 += line.strip()
print(pi_string)
print(len(pi_string))
print(pi_string2)
print(len(pi_string2))
"""
3.1415926535 8979323846 2643383279
36
3.141592653589793238462643383279
32
"""
"""
读取文本时,Python将所有文本都解读为字符串,若作为数字就要使用int() or float()
"""
filename = 'pi01.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[:52] + "...")
print(len(pi_string))
birthday = input("Enter your birthday:")
if birthday in pi_string:
"""圆周率中包含你的生日吗"""
print("Your birthday appears in the pi.")
else:
print("Your birthday does not appear in the pi.")
filename = 'po.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
file_object.write("That's a joke.")
"""po.txt
I love programming.That's a joke. 写入内容在一行
"""
with open(filename,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("That's a joke.\n")
with open(filename,'a') as file_object:
file_object.write("He love programming.\n")
file_object.write("That's a joke too.\n")
"""
Python使用被称为异常的特殊对象来管理程序执行期间的错误。
每当程序发生错误,会创建一个异常对象。如果编写了处理该异常的代码,程序将继续运行。
未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
异常是使用try-except代码块处理的。try-except让Python执行指定操作。
"""
print(5/0)
"""
Traceback (most recent call last):
File "D:\python_work\practice22.py", line 12, in
print(5/0)
ZeroDivisionError: division by zero ①
"""
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
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("\nSecond number:")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
print(contents)
"""
Traceback (most recent call last):
File "D:\python_work\practice22.py", line 5, in
with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
"""
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
print(contents)
except FileNotFoundError:
msg = "Sorry,the file " + filename + " does not exist."
print(msg)
title = 'Alice in wonderland'
print(title.split())
filename = 'aa.txt'
try:
with open(filename) as obj:
contents = obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exit"
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as obj:
contents = obj.read()
except FileNotFoundError:
msg = "Sorry,the file " + filename + " does not exit ."
print(msg)
"""
except FileNotFoundError: # ②使用 pass 替换 msg... 和 print(msg)
pass
"""
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'alice.txt'
count_words(filename)
filenames = ['aa.txt','bb.txt','cc.txt']
for filename in filenames:
count_words(filename)
"""
Sorry,the file alice.txt does not exit .
The file aa.txt has about 18 words.
Sorry,the file bb.txt does not exit .
Sorry,the file cc.txt does not exit .
"""
"""代码修改见②,运行结果如下
Sorry,the file alice.txt does not exit .
The file aa.txt has about 18 words.
"""
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
import json
username = input("What's your name ?")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back," + username)
with open(filename) as obj:
username = json.load(obj)
print("Welcome back," + username)
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What's your name?")
with open(filename,'w') as f_obj:
jsondump(username,f_obj)
print("We'll remember you when you come back," + username)
else:
print("Welcome back" + username)
import json
def greet_user():
"""问候用户,并指出其名字"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What's your name?")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back," + username)
else:
print("Welcome back," + username)
greet_user()
import json
def get_stored_username():
"""如果存储了用户名,就获取他"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back," + username)
else:
username = input("What's your name?")
filename = 'username.json'
with open(filename) as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back," + username)
greet_user()
import json
def get_stored_username():
"""如果存储了用户名,就获取他"""
--snip--
def get_new_username():
"""提示用户输入用户名"""
username = input("What's your name?")
filename = 'username.json'
with open(filename) as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
"""问候用户,并指出名字"""
username = get_stored_username()
if username:
print("Welcome back," + username)
else:
username = get_new_username()
print("We'll remember you when you come back," + username)
greet_user()