Those common functions of OS modules that you must know (with built-in variables)

OS module

This module provides various functions that allow you to manipulate file paths and check path-related information such as existence, file extension, directory name, and more.

1.1 Commonly used functions

Some of the commonly used functions include:

  1. os.path.join(*paths): This function is used to intelligently connect one or more path components . It accepts multiple arguments and returns a new path string concatenated with appropriate path separators, which may vary depending on the underlying operating system.

  2. os.path.abspath(path): This function returns the absolute path version of the specified path . It will resolve any symbolic links and replace relative paths with absolute paths.

  3. os.path.exists(path): This function checks whether the given path exists in the file system and returns if it exists True, otherwise it returns False.

  4. os.path.isdir(path): Returns if the specified path points to an existing directory, Trueotherwise False.

  5. os.path.isfile(path): Returns if the specified path points to an existing file, Trueotherwise False.

  6. os.path.basename(path): Returns the base name of the path , i.e. the last component of the path,Generally used to represent file names

  7. os.path.dirname(path): Returns the directory name of the path, that is, all parts of the path except the last component.

  8. os.path.splitext(path): Split the path into a tuple (root, ext), where rootis the part without the extension, extbut the file extension (including the dot).

1.2 Usage examples

Here's os.pathan example of how to use it:

import os

path = "/home/user/documents/sample.txt"

print("拼接后的路径:", os.path.join("/home", "user", "documents", "file.txt"))
print("绝对路径:", os.path.abspath(path))
print("路径是否存在?", os.path.exists(path))
print("是一个目录?", os.path.isdir(path))
print("是一个文件?", os.path.isfile(path))
print("文件基本名称:", os.path.basename(path))
print("目录名:", os.path.dirname(path))
print("拆分扩展名:", os.path.splitext(path))

1.3 Built-in variables

Built-in variables do not belong in this section, but are often used in conjunction with the os.path module. Therefore, built-in variables have been added to this section.

  1. __name__: Indicates the name of the current module. When the module is executed directly, __name__the value is '__main__'; when the module is imported, __name__the value is the name of the module.

  2. __file__: is one of the special built-in variables that represents the file path of the current module (or script).

  3. __doc__: Represents the documentation string of the current module (or function, class). A docstring is a string that precedes a module, function, or class definition and provides a brief description and explanation of the module, function, or class.

  4. __package__: Indicates the package name to which the current module belongs. For top-level modules (non-package modules), __package__the value is None.

  5. __builtins__: is a dictionary containing Python's built-in functions, exceptions, and other built-in objects.

  6. __loader__: Represents the module loader object that loads the current module.

  7. __spec__: Represents the specification object (ModuleSpec) of the current module. The specification object contains metadata about the module, such as file paths, package information, etc.

  8. __annotations__: Used to store type annotation information of variables.

  9. __cached__: Only available in compiled mode, represents the cache file path of the current module.

  10. __package__: Indicates the package name to which the current module belongs.

  11. __class__: Used in classes to indicate the class to which the current instance belongs.

1.4 Appendix: Detailed explanation of built-in variables

  1. __name__:
    __name__Indicates the name of the current module . When the module is executed directly, __name__the value is '__main__'; when the module is imported, __name__the value is the name of the module.

    Example:
    Suppose we have a example_module.pymodule file named with the following code:

    # example_module.py
    
    def hello():
        print("Hello from example_module!")
    
    print("Module name:", __name__)
    
    if __name__ == "__main__":
        hello()
    

    When we run it directly example_module.py, the output will be:

    Module name: __main__
    Hello from example_module!
    

    When we import in another script example_module.py, the output will be:

    Module name: example_module
    
  2. __file__:
    __file__Indicates the file path of the current module (or script). It is a built-in variable used to get the absolute file path of the current Python script.

    In Python, when a script (module) is executed, the Python interpreter stores the absolute file path of the script in a __file__variable. This allows us to get the file path of the current script in the code, so that we can manipulate the file where the script is located or find the path of the resource file.

    Notice:__file____file__Only available in script files, but undefined in interactive interpreters or code that directly executes the interpreter.

    The following is an __file__example of using to get the current script file path:

    Let's say we have a example_script.pyscript file named with the following code:

    # example_script.py
    
    import os
    
    current_script_path = os.path.abspath(__file__)
    print("当前脚本文件路径:", current_script_path)
    

    When we run it directly example_script.py, the output will be:

    当前脚本文件路径: /path/to/example_script.py
    
  3. __doc__:
    __doc__Represents the documentation string of the current module (or function, class). A docstring is a string that precedes a module, function, or class definition and provides a brief description and explanation of the module, function, or class.

    Example:
    In the above example_module.py, we can add a docstring to describe the functionality of the module:

    # example_module.py
    
    """This is an example module."""
    
    def hello():
        """Prints a greeting message."""
        print("Hello from example_module!")
    
    print("Module name:", __name__)
    
    if __name__ == "__main__":
        hello()
    

    In the Python interactive interpreter, we can __doc__view the module’s docstring by accessing:

    import example_module
    
    print(example_module.__doc__)
    

    Output:

    This is an example module.
    
  4. __package__:
    __package__Indicates the package name to which the current module belongs.

    Example:
    Suppose we have a package structure as shown below:

    my_package/
    │── __init__.py
    │── module_a.py
    └── subpackage/
        │── __init__.py
        └── module_b.py
    

    In module_b.py, we can __package__get the package name using:

    # module_b.py
    
    print("Package name:", __package__)
    

    When we import module_b.py, the output will be:

    Package name: my_package.subpackage
    
  5. __builtins__:
    __builtins__is a dictionary that contains Python’s built-in functions, exceptions, and other built-in objects.

    Example:
    We can __builtins__access some built-in functions like print()and using len():

    print("Built-in print function:", __builtins__.print)
    print("Built-in len function:", __builtins__.len)
    

    Output:

    Built-in print function: <built-in function print>
    Built-in len function: <built-in function len>
    

    __builtins__Usually not used directly because built-in functions and objects are already globally accessible.

  6. __loader__:
    __loader__Represents the module loader object that loads the current module.

    Example:
    We can access within a module __loader__to find out which loader loaded the module:

    # example_module.py
    
    print("Module loader:", __loader__)
    

    The output usually shows the type of loader and related information.

  7. __spec__:
    __spec__Represents the specification object (ModuleSpec) of the current module. The specification object contains metadata about the module, such as file paths, package information, etc.

    Example:
    We can access in a module __spec__to understand the specification information of the module:

    # example_module.py
    
    print("Module specification:", __spec__)
    

    The output typically displays the properties and related information of the specification object.

  8. __annotations__:
    __annotations__Used to store type annotation information of variables.

    Example:
    Suppose we have a function using type annotations:

    def add(a: int, b: int) -> int:
        return a + b
    
    print("Annotations:", __annotations__)
    

    Output:

    Annotations: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
    

    __annotations__Stores the type information of parameters and return values.

  9. __cached__:
    __cached__Only available in compiled mode, indicating the cache file path of the current module. When the Python interpreter runs a module, it caches the module's bytecode to the hard disk so that it can be loaded quickly next time.

    Example:
    After running the module in compiled mode, you can __cached__view the path to the cached file by accessing:

    # example_module.py
    
    print("Cached file path:", __cached__)
    

    The output usually shows the path to the cached file.

  10. __package__:
    __package__Indicates the package name to which the current module belongs.

  11. __class__:
    __class__Used in classes to indicate the class to which the current instance belongs.

    Example:
    Let's say we have a class Person:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def say_hello(self):
            print(f"Hello, I'm {
            
            self.name}.")
    
    person = Person("Alice", 30)
    print(person.__class__)
    

    Output:

    <class '__main__.Person'>
    

    __class__Returns Personthe type object of the class.

Guess you like

Origin blog.csdn.net/qq_44824148/article/details/131877668