Python文件和异常(五)
2022-09-06 22:57:37

一、从文件中读取数据

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())

1、逐行读取

with open('pi.txt') as f:
    for line in f:
        print(line.rstrip())

2、读取文件以列表格式返回

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')

四、异常

1、处理ZeroDivisionError异常

try-except代码块

try:
    print(2/0)
except ZeroDivisionError:
    print('by zero')

2、else代码块

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)

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......