• py_创建文件以及写入读取数据+异常处理


    import readline
    import math
    import json
    '''
    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]
    '''
    

      

  • 相关阅读:
    Python
    Python
    Redis
    android和.net webservice中的DES加密算法
    android studio中使用recyclerview小白篇(四)
    android studio中使用recyclerview小白篇(三)
    android studio中使用recyclerview小白篇(二)
    android studio中使用recyclerview小白篇(一)
    Fragment之间通过add切换时的显示与隐藏
    android报错:org.ksoap2.SoapFault cannot be cast to org.ksoap2.serialization.SoapObject
  • 原文地址:https://www.cnblogs.com/c-jw/p/12651948.html
Copyright © 2020-2023  润新知