zoukankan      html  css  js  c++  java
  • 初识python之包与内置模块

    课堂笔记:

    一、常用模块(内置模块)

    1、time
    # import time # 导入time模块
    # # 获取时间戳
    # print(time.time())
    #
    # # 等待2秒
    # time.sleep(2)
    #
    # print(time.time())

    2、 os
    import os
    # 与操作系统中的文件进行交互
    # 判断tank.txt文件是否存在
    # print(os.path.exists('tank.txt')) # True
    # print(os.path.exists('tank1.txt')) # False
    # print(os.path.exists(r'D:\python_files\day03\tank.txt')) # True
    #
    # # 获取当前文件的根目录
    # print(os.path.dirname(__file__)) # D:/python_files/day03

    3、 sys
    import sys
    # 获取python在环境变量中的文件路径
    # print(sys.path)
    # # 把项目的根目录添加到环境变量中
    # sys.path.append(os.path.dirname(__file__))
    # print(sys.path)


    4、 json
    import json
    # user_info = {
    # 'name': 'tank',
    # 'pwd': '123'
    # }

    5、 dumps: 序列化
    # 1、把字典转行成json数据
    # 2、再把json数据转换成字符串
    # res = json.dumps(user_info)
    # print(res)
    # print(type(res))
    #
    # with open('user.json', 'wt', encoding='utf-8') as f:
    # f.write(res)

    6、 loads: 反序列化
    # json.loads()
    # 1、把json文件的数据读到内存中
    # with open('user.json', 'r', encoding='utf-8') as f:
    # # 读取得到的是字符串
    # res = f.read()
    # # print(type(res))
    # # loads把json格式的字符串转换成dict类型
    # user_dict = json.loads(res)
    # print(user_dict) # {'name': 'tank', 'pwd': '123'}
    # print(type(user_dict)) # <class 'dict'>


    7、dump
    # user_info = {
    # 'name': 'tank',
    # 'pwd': '123'
    # }
    # with open('user_info.json', 'w', encoding='utf-8') as f:
    # # str1 = json.dumps(user_info)
    # # f.write(str1)
    # # dump: 自动触发f.write方法
    # json.dump(user_info, f)


    8、load
    with open('user_info.json', 'r', encoding='utf-8') as f:
    # res = f.read()
    # user_dict = json.loads(res)
    # print(user_dict)

    # load:自动触发f.read()
    user_dict = json.load(f)
    print(user_dict)


  • 相关阅读:
    JAVA WEBSERVICE服务端&客户端的配置及调用(基于JDK)
    An internal error occurred during: "Launching New_configuration"
    Android 创建虚拟机时“提示no system images installed for this target”
    [转] 传说中的WCF(2):服务协定的那些事儿
    [转] 传说中的WCF
    python的包管理
    python入门常用方法(转json,模拟浏览器请求头,写入文件)
    python读写数据篇
    python跳坑手记
    python爬虫入门篇
  • 原文地址:https://www.cnblogs.com/lweiser/p/11020507.html
Copyright © 2011-2022 走看看