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]
'''
原文地址:https://www.cnblogs.com/c-jw/p/13806706.html