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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章