玖叶教程网

前端编程开发入门

Python库函数之os和pathlib库对比

20230522星期一:

库os:

import os,time

filename = r"E:\资料\PythonTip.xlsx"
file = os.path.realpath(filename)
os.system(f'explorer/select,{file}') # 打开文件 filename 所在文件夹,并定位到该Excel文件;
# 注意:/select,这两个之间不能有空格,不然就是直接打开文件了,不会打开文件夹并定位到文件
time.sleep(2)
os.startfile(file) # 自动打开该Excel文件


"""
os.listdir(path) :# 传入任意一个path路径,返回的是该路径下所有文件和目录组成的列表
os.path.exists(path):# 传入一个path路径,判断指定路径下的目录是否存在。存在返回True,否则返回False;
os.walk():# 扫描某个指定目录下所包含的子目录和文件(类似:pathlib.Path.rglob)
os.unlink(path) # 删除指定文件
os.mkdir(path) :# 传入一个path路径,创建单层(单个)文件夹;如果文件夹已经存在,就会报错
os.rmdir(path) :# 传入一个path路径,删除指定路径下的文件夹;该方法只能删除空文件夹,删除非空文件夹会报错;
os.path.join(path1,path2):# 传入两个path路径,将该路径拼接起来,形成一个新的完整路径;
os.path.split(path)   :# 传入一个完整的path路径,将其拆分为绝对路径和文件名2部分;
os.path.basename(path) :# 传入一个完整的文件路径,只获取其文件名;
os.path.isdir(path)  :# 传入一个完整的文件路径,判断它是否是文件夹;
os.path.isfile(path) :# 传入一个完整的文件路径,判断它是否是文件;
os.path.getsize(path) :# 传入一个完整的文件路径,返回该文件的大小;
os.path.dirname(__file__):# F:/Py_Develop/PO3_1122/Pachong,获取当前文件夹的绝对路径
os.path.abspath(__file__):# F:\Py_Develop\PO3_1122\Pachong\1.py,获取文件所在的绝对路径
"""



os.walk():方法妙用:
"""
    fn_list = os.walk(fn)
    for root_path,dirs,files in fn_list:
        for file in files:
            if file.endswith(file_type):
                list_box.insert(tk.END,root_path + '\\' + file)
"""


库pathlib:

"""
@Project : For_Python_Pro
@File : pathlib库函数.py
@Author : Administrator
@Time : 2023/5/15 21:49
@Product : PyCharm
"""

import pathlib
from pathlib import Path
# python版本大于3.4都自带标准库pathlib:
# pathlib极大地简化了路径相关操作:


# 1,获取目录:
print(Path.cwd()) # 返回文件当前所在目录 # E:\For_Python_Pro\PyDevelop\PO3_1122\allData_Python\Python_各种库函数\pathlib库
print(Path.home()) # 用户主目录 # C:\Users\Administrator


# 2,目录拼接,直接使用 斜杠 / 操作符,比如创建子目录:
currentPath = Path.cwd()
newPath = currentPath / 'python-100'
print(f"新目录为 {newPath}") # 新目录为 E:\For_Python_Pro\PyDevelop\PO3_1122\allData_Python\Python_各种库函数\pathlib库\python-100


# 3,创建,删除目录:
# Path.mkdir(),创建给定路径的目录
# Path.rmdir(),删除该目录,目录文件夹必须为空
currentPath = Path.cwd()
makePath = currentPath / 'python-101'
# makePath.mkdir()
print(f"创建的目录为 {makePath}") # 创建的目录为 E:\For_Python_Pro\PyDevelop\PO3_1122\allData_Python\Python_各种库函数\pathlib库\python-101


# 4,读写文件:
# Path.open(mode='r'),以'r'格式打开 Path 路径下的文件,若文件不存在即创建后打开
# Path.read_bytes(),打开 Path 路径下的文件,以字节流格式读取文件内容,等同于 open 操作文件的 'rb'格式
# Path.read_text(),打开 Path 路径下的文件,以 str 格式读取文件内容,等同于 open 操作的 'r'格式
# Path.write_text(),对 Path 路径下的文件进行写入操作,等同于 open 操作文件的 'w' 格式

currentPath = Path.cwd()
mkPath = currentPath / 'python-102.txt'
with mkPath.open('w') as f:
    f.write('python-102')
f = open(mkPath,'r')
print(f"读取的文件内容为 {f.read()} ")
f.close()

currentPath = Path.cwd()
mkPathText = currentPath / 'python-103-text.txt'
mkPathText.write_text('python-103-text')
print(f"读取文件的内容为 {mkPathText.read_text()} ")

str2byte = bytes('python-104',encoding='utf-8')
mkPathByte = currentPath / 'python-104-byte.txt'
mkPathByte.write_bytes(str2byte)
print(f"读取文件的内容为 {mkPathByte.read_bytes()} ")


# 5,获取文件所在目录的不同部分字段:
# Path.resolve(),通过传入文件名,返回文件的完整路径
# Path.name,可以获取文件的名字,包含后缀名
# Path.parent,返回文件所在的文件夹的名字
# Path.stem,获取文件名,不包含后缀名
# Path.suffix,获取文件的后缀名
# Path.anchor,获取文件所在盘符
textPath = Path("python-102.txt")
nowPath = textPath.resolve()
print(f"文件完整路径为 {nowPath} 类型为 {type(nowPath)}") # 文件完整路径为 E:\For_Python_Pro\PyDevelop\PO3_1122\allData_Python\Python_各种库函数\pathlib库\python-102.txt 类型为 <class 'pathlib.WindowsPath'>
print(f"文件完整名称为 {nowPath.name}") # 文件完整名称为 python-102.txt
print(f"文件所在文件夹名为 {nowPath.parent}") # 文件所在文件夹名为 E:\For_Python_Pro\PyDevelop\PO3_1122\allData_Python\Python_各种库函数\pathlib库
print(f"文件名为 {nowPath.stem}") # 文件名为 python-102
print(f"文件后缀名为 {nowPath.suffix}") # 文件后缀名为 .txt
print(f"文件所在盘符为 {nowPath.anchor}") # 文件所在盘符为 E:\


# 6,文件,路径是否存在判断:
# Path.exists(),判断 Path 路径是否指向一个已存在的文件或目录,返回True或False
# Path.is_dir(),判断 Path 是否是一个路径,返回True或False
# Path.is_file(),判断 Path 是否是一个文件,返回True或False
currentPath = Path.cwd() / 'python'
print(currentPath.exists()) # False
print(currentPath.is_dir()) # False
currentPath.mkdir() # 创建 python 文件夹
print('文件夹创建以后:',currentPath.exists()) # 文件夹创建以后: True
print('文件夹创建以后:',currentPath.is_dir()) # 文件夹创建以后: True

currentPath = Path.cwd() / 'python.txt'
print(currentPath.exists()) # False
print(currentPath.is_file()) # False
f = open(currentPath,'w') # 创建 python 文件
f.close()
print('文件创建以后:',currentPath.exists()) # 文件创建以后: True
print('文件创建以后:',currentPath.is_file()) # 文件创建以后: True


# 7,文件统计以及匹配查找:
# Path.iterdir(),返回Path目录下的所有文件,返回的是一个生成器类型
# Path.glob(pattern),返回Path目录文件夹下所有与pattern匹配的文件,返回的是一个生成器类型
# Path.rglob(pattern),返回Path路径下所有子文件夹中与pattern匹配的文件,返回的是一个生成器类型:

# 使用 Path.iterdir() 获取当前文件夹下的所有文件,并根据后缀名,统计其个数
from collections import Counter
currentPath = Path.cwd()
gen = (i.suffix for i in currentPath.iterdir())
print(Counter(gen))

gen = (i.suffix for i in currentPath.glob("*.txt"))
print(Counter(gen))
gen = (i.suffix for i in currentPath.rglob("*.txt"))
print(Counter(gen))


发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言