#coding:utf-8
#write file 覆盖之前的文件
#with open("1.txt","w") as b:
# b.write("today is a good day")
#write file 在之前的文件后面新加
#with open("1.txt","a") as b:
# b.write("\ntoday is a ok day")
#读取和写入模式打开,覆盖之前的内容并且第一行留空
with open("1.txt","r+") as b:
b.write("\ntoday is a r day")
#read file
#默认为只读r
with open("1.txt") as a:
'''
c = a.read()
print(c.rstrip())
'''
'''
for line in a:
print(line.rstrip())
'''
lines = a.readlines()
for line in lines:
print(line.rstrip())
#json数据存储
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)
#异常
try:
print(5/0)
except ZeroDivisionError:
print("zero")
try:
print(5/0)
except ZeroDivisionError:
#什么也不做
pass
try:
print(5/2)
except ZeroDivisionError:
print("zero")
else:
print("ok")
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)