filename ='pi_digits.txt'withopen(filename)as file_object:
lines = file_object.readlines()"""空字符串的目的是让该变量是字符数据类型"""
pi_string =''for line in lines:
pi_string += line.rstrip() 删除后面的一行
pi_string += line.strip() 删除后面的空格
print(pi_string)print(len(pi_string))
结果为
10.1.6 包含一百万位的大型文件
10.1.7 圆周率值中包含你的生日吗
pi_string =''for line in lines:
pi_string += line.rstrip() 删除后面的一行
pi_string += line.strip() 删除后面的空格
birthday =input("Enter your birthday, in the form mmddyy: ")"""使用if语句判断pi_string字符串中是否有birthday变量中的字符串,字符串不一定要相等,包含即可
"""if birthday in pi_string:print("yes")else:print("no")
10.2 写入文件
10.2.1 写入空文件
10.2.2 写入多行
filename ='pi_digits.txt'""" 'w' 会把文件之前的内容全部清除,再写"""withopen(filename,'w')as file_object:
file_object.write('I love programming. \n')
file_object.write('I love running. \n')
pi_digits.txt
10.2.3 附加到文件
filename ='pi_digits.txt'""" 'a' 不会把文件之前的内容全部清除,只会在后面追加"""withopen(filename,'a')as file_object:
file_object.write('I am crazy!. \n')
file_object.write('I am master!. \n')
结果为
10.3 异常
10.3.1 处理 ZeroDivisionError 异常
10.3.2 使用 try-except 代码块
try:print(5/0)except ZeroDivisionError:print("You can't divide by zero!")
结果为
10.3.3 使用异常避免崩溃
10.3.4 else 代码块
print("Give me two numbers, and I'll divide them.")print("Enter 'q' to quit.")whileTrue:
first_number =input("\nFirst number: ")if first_number =='q':break
second_number =input("\nSecond number: ")try:
answer =int(first_number)/int(second_number)except ZeroDivisionError:print("You can't divide by 0!")else:print(answer)
结果为
10.3.5 处理 FileNotFoundError 异常
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+filename +" does not exist."print(msg)
结果为
10.3.6 分析文本
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+filename +" does not exist."print(msg)else:# 计算文件大致包含多个单词"""split()函数根据一个字符串创建一个单词列表"""
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+"words.")
结果为
alice.txt 文件
10.3.7 使用多个文件
defcount_words(filename):try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+filename +" does not exist."print(msg)else:# 计算文件大致包含多个单词"""split()函数根据一个字符串创建一个单词列表"""
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+"words.")
filename ='alice.txt'
count_words(filename)
filenames =['alice.txt','pi_digits.txt']for filename in filenames:
count_words(filename)
import json
usernames =input("What is your name? ")
filename ='username.json'withopen(filename,'w')as f_obj:"""把usernames 的值放入 f_obj 中"""
json.dump(usernames, f_obj)print("We'll remember you when you come back ,"+ usernames +"!")