文件
# file tyr except
# 所在的目录中查找pi_digits.txt
# 关键字with在不再需要访问文件后将其关闭
# 1 读取文件
filename = 'pi_digitis.txt'
with open(filename) as file_object:
contents = file_object.read()
print(contents)
print("")
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
#使用文件中得内容
pi_string = ''
pi_string_1 = ''
for line in lines:
pi_string += line.rstrip()
pi_string_1 += line.strip()
print(pi_string)
print(len(pi_string))
print(pi_string_1)
print(len(pi_string_1))
# 2 写入文件
filename = 'programming.txt'
# 打开文件时,可指定读取模
# 式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如果
# 你省略了模式实参,Python将以默认的只读模式打开文件
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
file_object.write("\n ")
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
# 附件
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
异常
# try except
#处理ZeroDivisionError异常的try-except
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
# try-except代码块后面还有其他代码,程序将接着运行,因为已经告诉了Python如何处
# 理这种错误。
# # 依赖于try代码块成功执行的代码都应放到else代码块
# 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 0!")
# else:
# print(answer)
# 处理 FileNotFoundError 异常
print("")
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
# Python有一个pass语句,可在代码块中使用它来让Python什么都不要做
print("")
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# msg = "Sorry, the file " + filename + " does not exist."
# 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)
# 使用json.dump()来存储这组数字,而第二个程序将使用json.load()。
import json
numbers = [2,3,4,5,6,7,8,9]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)