SoFunction
Updated on 2025-04-17

Detailed explanation of the module for file path processing in Python

1. Preface

Project operation environment:

  • Platform: Window11
  • Locale: Python 3.8
  • Running Environment 1: PyCharm 2021.3
  • Running Environment 2: Jupyter Notebook 7.3.2
  • Framework: PyTorch 2.5.1 (CUDA11.8)

2. File path check module

I believe that many people, like Maomao, have never carefully studied Python file paths. Previous knowledge about file path output, jump, and complete paths came entirely from Java and linux. For example, if you say you can use it, it is of course possible. But this is really unintuitive. As a magical language, Python must have other more intuitive file path processing methods. Don’t say it, there is really, today the cat will take you to see.

2.1 Module usage method

If you want to take something out of a file or put the thing you generated into a file, you must use such a file path module. The function is to see what you need, how it is placed in which folder at the path level, or taken out from the folder.

Don’t just say that you need to look at the directory structure next to PyCharm. Maomao was cheated for more than an hour today. Because we put the code for deep learning on the server, but the code written in the native PyCharm, the directory structure of the two is likely to be different. If you don’t pay attention, you will easily be cheated like Maomao for several hours. Therefore, every time you process things related to the file path, it is recommended to use Maomao’s module to check it first.

2.2 Submodule 1: Current path output

from pathlib import Path
 
# Get the directory where the current script is located and output the absolute pathscript_parent = Path(__file__).resolve()
print(f"The full path to the current script directory: {script_parent}")

Path(__file__): Create a path object. Converts the file path of the current script to an object.

.resolve(): resolves to an absolute path. The relative path is converted to an absolute path (such as ./ → /home/user/project/).

Path(__file__)          # /usr/bin/myscript (symlink path)Path(__file__).resolve() # /home/user/project/ (actual path)

2.3 Submodule 2: Path jump

Through the previous module, we can see the directory where our code is located. Now we want to implement path jump, because the essence of the path is to get what we want into a path we want, or send our things to where we want, which involves path jumping. Path jump is divided into: parent path jump + child path jump.

Parent path jumps:

The essence is to exit the current path and return to the parent directory.

from pathlib import Path
 
# Get the parent directory of the directory where the current script is located and output the absolute pathscript_parent = Path(__file__).resolve().parent
print(f"The full path to the parent directory: {script_parent}")

.parent: Get the parent directory. Returns the parent directory of the path. If the path is /home/user/project/:

Path(__file__).resolve().parent # /home/user/project

Subpath jump:

The essence is to go deeper into the current directory, so it is to add a part of the path content after the directory path.

script_dir = Path(__file__).resolve().
target_dir = script_dir / "Real-ESRGAN-main" / "inputs"
target_dir1 = script_dir / "Real-ESRGAN-main"

/: Just follow the path name you want to enter, you can use it one level after another.

.parent: Also allows one level to be superimposed

2.4 Submodule 3: Display of the complete path of the root directory

def generate_file_tree(directory: str, max_depth: int = 3) -> str:
    """Generate a formatted directory tree (optimize recursive performance)"""
 
    def _tree(path: Path, prefix: str = "", depth=0) -> str:
        if depth > max_depth:
            return ""
 
        try:
            items = sorted((), key=lambda x: (not x.is_dir(), ()))
        except PermissionError:
            return f"{prefix}└── 🔒 Insufficient permissions"
        except FileNotFoundError:
            return f"{prefix}└── ❓ The directory has disappeared"
 
        contents = []
        for index, item in enumerate(items):
            is_last = index == len(items) - 1
            connector = "└── " if is_last else "├── "
 
            # File type identification            if item.is_symlink():
                icon = "🔗"
                suffix = f" -> {()}"
            elif item.is_dir():
                icon = "📁"
                suffix = ""
            else:
                icon = "📄"
                suffix = f" ({().st_size // 1024} KB)" if ().st_size > 0 else " (empty file)" 
            entry = f"{prefix}{connector}{icon} {}{suffix}"
            (entry)
 
            # Recursively process subdirectories            if item.is_dir() and not item.is_symlink():
                extension = "    " if is_last else "│   "
                (_tree(item, prefix + extension, depth + 1))
 
        return "\n".join(contents) if contents else f"{prefix}└── 🗑 Empty directory"
 
    root = Path(directory)
    if not ():
        return f"❌ The path does not exist: {directory}"
 
    return f"🌳 Directory tree {root} (Depth Limit: {max_depth})\n" + _tree(root)

Through the above code, we can find all the complete path directories below the specified path. Through the first three modules, we can return to the root directory where our code is located, and through this code, we can find all the directory structures under the root directory.

2.5 Submodule 4: Target Path Check

Based on the previous three submodules, we can already find the target path. Now it is enough to verify whether the target path exists, so the target path needs to be checked.

def path_exists(path_str: str) -> bool:
    """General Path Existence Check"""
    return Path(path_str).exists()

3. Full module display

"""
 path_analyzer.py - Multifunctional path analysis tool
 Functions include:
 1. Display of the script's own path information
 2. Smart directory tree generation
 3. Path existence verification
 4. Recursive depth control
 """
 
from pathlib import Path
import argparse
 
# Get script path informationscript_path = Path(__file__).resolve()
script_dir = script_path.parent
 
 
def show_script_info():
    """Show script's own path information"""
    print(f"📜 Script path: {script_path}")
    print(f"📂 Script Directory: {script_dir}\n")
 
 
def generate_file_tree(directory: str, max_depth: int = 3) -> str:
    """Generate a formatted directory tree (optimize recursive performance)"""
 
    def _tree(path: Path, prefix: str = "", depth=0) -> str:
        if depth > max_depth:
            return ""
 
        try:
            items = sorted((), key=lambda x: (not x.is_dir(), ()))
        except PermissionError:
            return f"{prefix}└── 🔒 Insufficient permissions"
        except FileNotFoundError:
            return f"{prefix}└── ❓ The directory has disappeared"
 
        contents = []
        for index, item in enumerate(items):
            is_last = index == len(items) - 1
            connector = "└── " if is_last else "├── "
 
            # File type identification            if item.is_symlink():
                icon = "🔗"
                suffix = f" -> {()}"
            elif item.is_dir():
                icon = "📁"
                suffix = ""
            else:
                icon = "📄"
                suffix = f" ({().st_size // 1024} KB)" if ().st_size > 0 else " (empty file)" 
            entry = f"{prefix}{connector}{icon} {}{suffix}"
            (entry)
 
            # Recursively process subdirectories            if item.is_dir() and not item.is_symlink():
                extension = "    " if is_last else "│   "
                (_tree(item, prefix + extension, depth + 1))
 
        return "\n".join(contents) if contents else f"{prefix}└── 🗑 Empty directory"
 
    root = Path(directory)
    if not ():
        return f"❌ The path does not exist: {directory}"
 
    return f"🌳 Directory tree {root} (Depth Limit: {max_depth})\n" + _tree(root)
 
 
def path_check(path_str: str) -> dict:
    """Enhanced Path Check"""
    path = Path(path_str)
    status = {
        'exists': (),
        'is_file': path.is_file(),
        'is_dir': path.is_dir(),
        'size': ().st_size if () else 0
    }
    return status
 
 
def main():
    """Command Line Entry Point"""
    parser = (description="Path Analysis Tool")
    parser.add_argument('path', nargs='?', default=str(script_dir), help="Path to be analyzed (default is script directory)")
    parser.add_argument('-d', '--max-depth', type=int, default=3, help="Directory Tree Recursive Depth (Default 3)")
    parser.add_argument('-q', '--quiet', action='store_true', help="Silent mode (no script information is displayed)")
 
    args = parser.parse_args()
 
    if not :
        show_script_info()
 
    # Path validity check    check_result = path_check()
    if not check_result['exists']:
        print(f"❌ mistake:The path does not exist - {}")
        return
 
    # Generate directory tree    tree = generate_file_tree(, args.max_depth)
    print(tree)
 
    # Show statistics    print(f"\n📊 Path Statistics:")
    print(f"  - type: {'Table of contents' if check_result['is_dir'] else 'document'}")
    if check_result['is_dir']:
        print(f"  - Included items: {len(list(Path().iterdir()))}")
    else:
        print(f"  - File size: {check_result['size'] // 1024} KB")
 
 
if __name__ == "__main__":
    main()

Note that the above module code can be used directly. Only the content in def main needs to be modified is only the content in def main. The main thing is to adjust some functions of the complete module of the file path (all have been commented)

This is the introduction to this article about the detailed explanation of Python's module for file path checking. For more related Python file path checking content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!