1.读取文件
with open('learning_python.txt') as file_object:
context = file_object.read()
print(context)
with open('learning_python.txt') as file_object:
#遍历对象
for line in file_object:
print(line.rstrip())
print('\n')
with open('learning_python.txt') as file_object:
#逐行读取并将内容存储到列表,在with之外打印列表
lines = file_object.readlines()
for each in lines:
print(each.rstrip())
2.文件写入
# -*- coding: gbk -*-
file_name = 'create_write_file.txt'
with open(file_name,'w') as file_object:
file_object.write('使用open时需指明参数,即以何种模式打开文件,默认为只读模式\n')
file_object.write('写入文件时会刷新旧的内容,如果找不到目标文件会自动创建。\n')
file_object.write('python只能将字符串写入文件,write方法不会添加换行符。\n')
3.异常处理
类型:ZeroDivisionError,FileNotFoundError,TypeError,ValueError
#ZeroDivisiomnError
a = 15
b = 0
try :
print(a/b)
except ZeroDivisionError:
mesg = 'can not divide by 0!\n'
print(mesg)
#FileNotFoundError
file_name = 'abc.txt'
try:
with open(file_name) as obj:
txt = obj.read()
except FileNotFoundError:
print('can not find the file ' + file_name +'!\n')
else:
print(txt)
#ValueError
a = input("input a:\n")
b = input('input b:\n')
try:
c = int(a) + int(b)
except ValueError:
print('please input numbers!!\n')
else:
print(c)

4.存储数据
import json
file_name = 'number.json'
try:
with open(file_name) as obj:
num = json.load(obj)
except FileNotFoundError:
number = input('please input your favorious number:\n')
with open(file_name,'w') as obj:
json.dump(number,obj)
print('I get your favorious number '+ number + ' now!')
else:
print('your favorious number is '+num +'\n')
第一次输入;
非第一次输入: