文件和异常
打开文件
with open('MCR_license.txt') as file_obj:
contents = file_obj.read()
print(contents)
- 只能打开txt文件,不能打开pdf和office文件
- 路径分为相对路径和绝对路径
#相对路径
with open('files\MCR_license.txt') as file_obj:
#绝对路径
with open('E:\SVN\MCR_license.txt') as file_obj:
注意,绝对路径需要注意格式(中文,数字为首字母 都有可能报错)
- 逐行读取文件,这个比较重要,数据处理时常用
filename = 'files\MCR_license.txt'
with open(filename) as file_obj:
"""
读取文件内容
contents = file_obj.read()
print(contents)
"""
"""
逐行读取
for line in file_obj:
print(line.rstrip())
"""
lines = file_obj.readlines()
for line in lines:
print(line.strip())
写入文件
- 新建空文件写入
file = 'test.txt'
with open(file,'w') as file_obj:
file_obj.write('I love programming.')
- 替换原有文件
file = 'test.txt'
with open(file,'w') as file_obj:
file_obj.write('I love programming.\n')
file_obj.write('I think Python is a good language!\n')
with open(file,'w') as file_obj:
file_obj.write('I love Matlab.\n')
- 在原文件后写入
file = 'test.txt'
with open(file,'w') as file_obj:
file_obj.write('I love programming.\n')
file_obj.write('I think Python is a good language!\n')
with open(file,'a') as file_obj:
file_obj.write('I love Matlab.\n')
异常处理
类似于Matlab的 try-catch ;Python使用的时 try-except-else
try:
print(5/0)
except ZeroDivisionError:
print('Zero Division Error')
else:
print(20)
print(11)
step1:执行try的逻辑
如果,执行正常,再去执行else
否者,执行输出except的逻辑
step2:执行后面的逻辑(第8行)
使用这个的好处是,可以忽略运行过程中产生的失误,继续执行下去
这种处理的方式时防止程序崩溃,尤其在和用户交互的时候很有用
expect 如果执行时,不想执行任何操作,可以直接给pass
except:
pass
存储数据
使用 json 来存储数据,是常用的一种方法
在python中 使用 json ,需要两点
- 导入 json 库
import json
- 使用两个函数对数据存储和载入
json.dump() #存储
json.load() #载入
比如:
import json
numbers = [1,2,3,4,36,8,6,11]
#写入数据
filename = 'number.json'
with open(filename,'w') as file_obj:
json.dump(numbers,file_obj)
#载入数据
with open(filename) as file_obj:
num = json.load(file_obj)
print(num)