(python) system path and file operations - os and pathlib


Preface

pathlib 和 os 是 Python 中用于处理文件路径和文件系统操作的两个模块。os 模块提供了底层的操作系统相关功能;pathlib 提供了面向对象的路径操作接口。pathlib 模块实际上是在 os 模块的基础上进行了封装和扩展,提供了更高级别的接口,以简化路径操作和文件系统访问(如同C++和C的关系)

1. Traverse the files in the directory

(1) The simple operation code is as follows, just to get all the pictures in the folder (including all subfolders):

import os
from pathlib import Path

dir_path = "/path"

# 使用 os 模块
for root, dirs, files in os.walk(dir_path):
    """
    root:正在遍历的文件夹路径
    dirs:一个包含当前文件夹中所有子文件夹的列表
    files:一个包含当前文件夹中所有文件名的列表
    """
    for file in files:
        print(os.path.join(root, file))

# 使用 pathlib 模块
for file in Path(dir_path).rglob("*"):
"""
 rglob("*") 表示匹配当前目录及所有子目录中的任意文件或目录
"""
    if file.is_file():
        print(file)  # 完整的绝对路径
    # if file.is_dir():
    #    print("当前目录",file)

(2) Advanced - Actual scenario: A data set folder contains multiple sub-folders, and each sub-file contains three folders: mask, train, and val.
Insert image description here
Insert image description here
During the training phase, all train images and corresponding mask images must be read separately. (Usually, the original image format is jpg, and the mask image is png)

dir_path = r'C:/Users/Desktop/test'

dirs = []
for make_dir in Path(dir_path).glob("**"):  # ** 表示匹配任意层级的子目录
    # print(make_dir)  
    # print(make_dir.name)  # 只读取最后一个目录,如mask,train,val
    if make_dir.name == "train":
        files = list(make_dir.glob("*.[jpb][nmp][pg]"))  # 匹配满足文件扩展名为 ".jpg"".png"".bmp" 的文件
        dirs += files  # 获取所有train文件夹里的图片
        print(f'path:{
    
    make_dir}  filenumber:{
    
    len(files)}   all_files:{
    
    len(dirs)}')

# i.parent.parent回到表示两层父级,如: C:/Users/Desktop/test/111
# i.with_suffix(".png").name表示将文件扩展名改为.png,再只保留name(图片名字)
mask_dir = [f'{
    
    i.parent.parent / "mask" / i.with_suffix(".png").name}' for i in dirs]  

おすすめ

転載: blog.csdn.net/qq_43199575/article/details/133920892