Article directory
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:
-
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. -
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. -
os.path.exists(path)
: This function checks whether the given path exists in the file system and returns if it existsTrue
, otherwise it returnsFalse
. -
os.path.isdir(path)
: Returns if the specified path points to an existing directory,True
otherwiseFalse
. -
os.path.isfile(path)
: Returns if the specified path points to an existing file,True
otherwiseFalse
. -
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。 -
os.path.dirname(path)
: Returns the directory name of the path, that is, all parts of the path except the last component. -
os.path.splitext(path)
: Split the path into a tuple(root, ext)
, whereroot
is the part without the extension,ext
but the file extension (including the dot).
1.2 Usage examples
Here's os.path
an 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.
-
__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. -
__file__
: is one of the special built-in variables that represents the file path of the current module (or script). -
__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. -
__package__
: Indicates the package name to which the current module belongs. For top-level modules (non-package modules),__package__
the value isNone
. -
__builtins__
: is a dictionary containing Python's built-in functions, exceptions, and other built-in objects. -
__loader__
: Represents the module loader object that loads the current module. -
__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. -
__annotations__
: Used to store type annotation information of variables. -
__cached__
: Only available in compiled mode, represents the cache file path of the current module. -
__package__
: Indicates the package name to which the current module belongs. -
__class__
: Used in classes to indicate the class to which the current instance belongs.
1.4 Appendix: Detailed explanation of built-in variables
-
__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 aexample_module.py
module 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
-
__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.py
script 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
-
__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 aboveexample_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.
-
__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
-
__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 likeprint()
and usinglen()
: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. -
__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.
-
__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.
-
__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. -
__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.
-
__package__
:
__package__
Indicates the package name to which the current module belongs. -
__class__
:
__class__
Used in classes to indicate the class to which the current instance belongs.Example:
Let's say we have a classPerson
: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__
ReturnsPerson
the type object of the class.