面试题答案
一键面试实现引用的思路
- 获取项目根目录:通过相对路径或
sys.argv[0]
等方式确定项目根目录。 - 构建目标文件路径:基于项目根目录,拼接
docs/config.ini
路径。 - 确保路径兼容性:使用
os.path.join
或pathlib.Path
模块来处理路径,以确保在不同操作系统上路径引用的兼容性。
Python代码示例
import os
from configparser import ConfigParser
def get_project_root():
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def read_config():
root = get_project_root()
config_path = os.path.join(root, 'docs', 'config.ini')
config = ConfigParser()
config.read(config_path)
return config
if __name__ == "__main__":
config = read_config()
print(config.sections())
确保路径兼容性
- 使用
os.path.join
:该函数会根据当前操作系统的路径分隔符(Windows下为\
,Linux和macOS下为/
)来正确拼接路径。如示例代码中的os.path.join(root, 'docs', 'config.ini')
。 pathlib.Path
模块:pathlib.Path
是Python 3.4引入的面向对象的路径操作模块,同样会自动处理不同操作系统路径分隔符的差异。示例如下:
from pathlib import Path
from configparser import ConfigParser
def get_project_root():
return Path(__file__).parent.parent.parent
def read_config():
root = get_project_root()
config_path = root / 'docs' / 'config.ini'
config = ConfigParser()
config.read(str(config_path))
return config
if __name__ == "__main__":
config = read_config()
print(config.sections())
这里Path(__file__)
获取当前脚本文件路径,parent
属性可以获取父目录,通过多次调用parent
获取项目根目录,/
运算符用于拼接路径。注意config.read
需要传入字符串类型路径,所以使用str(config_path)
进行转换。