Python中如何无需硬编码绝对路径读取properties配置文件?
解决Python读取properties文件时的硬编码路径问题
我太懂这种硬编码绝对路径的坑了——换个环境部署直接炸锅!先帮你分析下之前的方法为啥失效,再给你两个靠谱的解决方案。
为啥你之前的路径拼接会触发KeyError?
你写的这段代码:
props = os.path.join( os.path.dirname("resources"), # folder where the python file is 'src/main/resources/configs.properties' )
问题出在os.path.dirname("resources")这里——你传入的是字符串"resources",不是脚本文件的真实路径!os.path.dirname对非路径字符串处理后会返回空字符串,最后拼接出来的路径是src/main/resources/configs.properties,这个路径是相对于当前工作目录的,而不是你项目的真实路径,所以config根本没读到文件,自然访问config['DB']就会报KeyError(因为配置文件内容没加载进来)。
方案一:基于当前脚本的相对路径构建(最常用)
利用Python的__file__变量获取当前脚本的绝对路径,然后根据你的项目结构拼接配置文件路径。假设你的项目结构是这样的:
PysparkETL/ ├─ src/ │ ├─ main/ │ │ ├─ resources/ │ │ │ └─ configs.properties │ │ └─ python/ # 你的脚本在这里 │ │ └─ your_script.py
那代码可以这么写:
import os import configparser # 获取当前脚本的绝对路径 current_script = os.path.abspath(__file__) # 获取脚本所在的目录 script_dir = os.path.dirname(current_script) # 拼接配置文件路径:从脚本目录往上到main,再进入resources # 这里的../数量根据你的脚本位置调整,比如脚本在src/main下,就用../resources config_path = os.path.join(script_dir, "../resources/configs.properties") # 用realpath解析相对路径里的../,得到标准的绝对路径 config_path = os.path.realpath(config_path) config = configparser.RawConfigParser() # 可以先打印路径验证是否正确 print(f"Loading config from: {config_path}") config.read(config_path) # 读取配置 dbname = config['DB']['dbname'] username = config['DB']['user'] password = config['DB']['password'] table = config['DB']['tablename'] driver = config['DB']['driver'] print(dbname)
方案二:基于项目根目录定位(更灵活)
如果你的脚本可能放在项目的不同子目录里,这种方法更靠谱——通过寻找项目的标志性目录(比如src)来定位根目录,再拼接配置路径:
import os import configparser # 从当前脚本目录开始,往上找项目根目录(包含src文件夹的目录) current_dir = os.path.dirname(os.path.abspath(__file__)) while not os.path.exists(os.path.join(current_dir, "src")): current_dir = os.path.dirname(current_dir) # 防止无限循环,找不到根目录时抛出异常 if current_dir == "/": raise FileNotFoundError("无法找到包含src文件夹的项目根目录") # 从根目录拼接配置文件路径 config_path = os.path.join(current_dir, "src/main/resources/configs.properties") config = configparser.RawConfigParser() config.read(config_path) # 读取配置...
额外注意事项
- 调试时先打印
config_path,确认路径是否正确,这是排查问题最快的方式 - 如果用PySpark打包成jar部署,可能需要用
pkg_resources从包资源读取配置,但普通脚本用上面两种方法足够 - 确保部署环境的项目结构和开发时一致,比如resources目录的位置不变
内容的提问来源于stack exchange,提问作者whatsinthename
相关产品推荐
相关产品推荐

