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)


  • 相关阅读:
    SQL学习记录
    Python 函数和变量作用域
    Python 使用socket实现一对多通信
    Flask wtforms validate_on_submit() 无法返回值问题
    Flask WTForm BooleanField用法
    Python3 中的nonlocal用法
    Python 实现二进制循环效果
    Python 各种类型转换
    第一章:数据结构
    Python Challenge
  • 原文地址:https://www.cnblogs.com/lweiser/p/11020507.html
Copyright © 2011-2022 走看看