zoukankan      html  css  js  c++  java
  • 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]
    '''
    

      

  • 相关阅读:
    weekly review 200819: Burn the midnight oil
    如何进行Android单元测试
    Android开发教程
    使用SQLite方式存储数据
    图像的平移、旋转及缩放
    JSON数据解析
    Android 多线程下载网络文件
    10套华丽的 Windows 8 Metro 风格图标【2000+免费图标】
    学习新技术的 10 个建议
    BugFree快速使用入门
  • 原文地址:https://www.cnblogs.com/c-jw/p/12651948.html
Copyright © 2011-2022 走看看