使用文件用with的好处
1.会在运行完后自动关闭文件
2.很简单
打开文件并读取
with open('c.xls','r') as t1: content = t1.read() print(content)
with open('c.xls','r') as t1: content = t1.read() con = t1.readlines() print(content) print(con)
open参数的解释:
+:表示拥有读和写功能
r表示只读,如果变成r+,表示可读可写,不能创建文件
w表示可写,w+表示可读可写,文件不存在则创建,存在则覆盖原先内容,原则就是创建一个新文件
a可写,a+表示可读可写,文件不存在则创建,追加内容在原本数据的末尾
扫描二维码关注公众号,回复:
1686737 查看本文章
-------------------------------------------
使用json文件读取和写入数据
import json try: with open('wxh.json', 'r') as filename: f = json.load(filename) #读取json文件 print ('your like number is :%s' % f) except: dig = raw_input("输入你喜欢的数字:") with open('wxh.json','w') as filename: json.dump(dig,filename) #数据写入json文件