在Python中,你可以使用`os`模块来获取根目录。以下是获取根目录的几种方法:
1. 使用`os.path.abspath`和`os.sep`获取根目录路径:
import osroot_dir = os.path.abspath(os.sep)print(root_dir)
2. 获取当前脚本文件的绝对路径,然后使用`os.path.dirname`获取项目根目录:
import oscurrent_path = os.path.abspath(__file__)project_dir = os.path.dirname(current_path)print(project_dir)

3. 使用正则表达式从当前文件的绝对路径中提取根目录:
import reimport osROOT_PATH = re.match(os.path.abspath(__file__), r'/(.*/)').group(1)print(ROOT_PATH)
4. 逐级向上查找包含`__init__.py`的目录作为根目录:
import osroot_dir = os.path.abspath(os.path.dirname(__file__))while not os.path.exists(os.path.join(root_dir, '__init__.py')):root_dir = os.path.dirname(root_dir)print(root_dir)
以上方法适用于获取系统根目录或项目根目录。请根据你的需求选择合适的方法
