py_文件读取+异常处理

import readline
import math
import json
#py文件读取+异常处理
'''
A:
第一行
第二行
第三行
'''
#从文件读取数据
with open("D:\A.txt") as f :
    content = f.read()
    print(content)
# with open一个file,当做一个对象,直接操作对象,读完之后自动将file释放

with open("D:\A.txt") as f :
    for line in f:
        print(line)
    print(line)
#列表
'''
B:
  第一行
    第二行
      第三行
'''
with open("D:\B.txt") as f2 :
    lines = f2.readlines()#列表
    for line in lines:
        print(line.strip())#去掉空格

#创建文件写入内容
file_path = r"D:\C.txt"
with open(file_path,"w") as fw:
    fw.write("写sss") #  写sss/n 换行


#异常处理:
file_path = r"D:\C.txt"
try:
    with open(file_path,"w") as fw:
        #fw.writeline("xxx") #  写sss/n 换行
        fw.write("xxxx")
except Exception as ex:
    print("出错了,请联系管理员!")
    print(ex)# 
else:
    print("写入成功")

#json文件写入读取

try:
    nums = [1,2,3,4,5]
    fileName = r"D:\d_Json.json"
    with open(fileName,"w") as fjson:
        fjson.write(nums)
except Exception as ex:
    print("出错了,请联系管理员!")
    print(ex)# 
else:
    print("写入成功")
'''
出错了,请联系管理员!
write() argument must be str, not lists
'''
# update
try:
    nums = [1,2,3,4,5]
    fileName = r"D:\d_Json.json"
    with open(fileName,"w") as fjson:
        json.dump(nums,fjson)
except Exception as ex:
    print("出错了,请联系管理员!")
    print(ex)# 
else:
    print("写入成功")
with open(fileName) as fjson:
    print(json.load(fjson))
'''
写入成功
[1, 2, 3, 4, 5]
'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_TestMG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值