• python路径库pathlib应用


    代码

    from pathlib import Path
    from tkinter import W
    
    # 常用
    p = Path('./util')
    print(type(p), p)
    print(type(str(p)), p)
    print(p.exists())
    print(p.is_dir())
    
    # 路径组合
    p2 = p / 'actions.py'
    print(type(p2), p2)
    
    # 文件名字及后缀
    p = Path('util/actions.py')
    print(p.name)
    print(p.stem)
    print(p.suffix)
    
    # 文件打开
    p3 = Path('t.txt')
    with open(p2) as f:
        print(f.read())
    
    p3 = Path('t.txt')
    with p3.open() as f:
        print(f.read())
    
    p3 = Path('t.txt')
    with open(p3, 'w') as f:
        f.write('abc')
    
    # 文件后缀
    p = Path('util/actions.py.gz')
    print(p.suffix) # .gz
    print(p.suffixes) # ['.py', '.gz']
    
    # 文件父目录
    p = Path('test/pw/util/actions.py')
    print(p.parent) # test/pw/util
    print(p.parents[0]) # test/pw/util
    print(p.parents[1]) # test/pw
    print(p.parents[2]) # test
    
    # 其他用法
    print([x for x in p.iterdir() if x.is_dir()]) # 遍历p目录下的所有文件夹
    print(list(p.glob('**/*.py'))) # 搜索当前路径下所有.py结尾的文件
    
    # windows调用
    p = Path('C:/Users/Administrator/Desktop/Pexe')
    print(p)
    print(p.exists())
  • 相关阅读:
    c# 菱形,三角形
    c#判断一个时间的时间段
    c# 1,判断是否为正整数 2 判断体重
    数据库 基础
    c#100 计算行李重量
    c#基础 1,100以内的与7相关的数字;2,计算器,
    String 类;Math 类
    常用的C#类
    冒泡排序与快速排序
    数据库基本知识
  • 原文地址:https://www.cnblogs.com/soymilk2019/p/15846600.html
Copyright © 2020-2023  润新知