open()函数
参数
- file 文件路径
- mode
mode参数 | 可做操作 | 若文件不存在 | 如何处理原内容 |
---|---|---|---|
r | 只可读 | 报错 | - |
r+ | 可读可写 | 报错 | 是 |
w | 只可写 | 创建 | 是 |
w+ | 可读可写 | 创建 | 是 |
a | 只可写 | 创建 | 否,追加 |
a+ | 可读可写 | 创建 | 否,追加 |
x | 只可写 | 创建 | - |
x+ | 可读可写 | 创建 | - |
# 一 f = open('pi.txt','r',encoding='utf-8') contents = f.read() print(contents) #二 with open('pi.txt') as line: content = line.read() # print(content) # rstrip()方法剔除字符串末尾空白 print(content.rstrip())
with open('pi.txt') as f: for line in f: print(line.rstrip())
lines = [] with open('pi.txt') as f: lines = f.readlines()· print(lines)
with open('a.txt','w',encoding='utf-8') as f: f.write('i like')
如果文件存在则在原文件内容后写入,如果不存在则创建写入
with open('a.txt','a',encoding='utf-8') as f: f.write('hello word')
try-except代码块
try: print(2/0) except ZeroDivisionError: print('by zero')
try-except-else
依赖于try代码块成功执行的代码都放在else代码块中
print('请输入两个数'); print('enter q to quit'); while True: firstNum = input('first num') if(firstNum=='q'): break secondNum = input('second num') if(secondNum =='q'): break try: result = int(firstNum)/int(secondNum) except ZeroDivisionError: print('can not') else: print(result)
json.dump()
- 参数
- 存储的数据
- 存储数据的文件对象
json.load()
- 参数
- 文件
import json # fileName = 'nums.json' # 存储json格式数据 # nums= [1,2,2,3,4,5,6] # with open(fileName,'w',encoding='utf-8') as f: # json.dump(nums,f) #读取json格式数据 with open(fileName) as f: nums = json.load(f) print(nums)