我找不到如何在Python中找到相对路径。该代码仅允许我使用绝对路径。
我想要的是
config = configparser.ConfigParser()
config.read('..\\main.ini',)
print(config.sections())
FilePaths = config['data']
DictionaryFilePath = FilePaths['DictionaryFilePath']
print(DictionaryFilePath)
它迫使我做什么
config = configparser.ConfigParser()
config.read('C:\\Users\\***confendential***\\OneDrive\\文档\\Python\\Chinese for practice\\ChineseWords\\app\\main.ini',)
print(config.sections())
FilePaths = config['data']
DictionaryFilePath = FilePaths['DictionaryFilePath']
print(DictionaryFilePath)
有任何想法吗???
是Onedrive吗?
总结一下,如果您只是这样做
config.read('..\\main.ini',)
那么您的程序期望文件main.ini
位于您执行程序的位置的父目录中。
通常,您需要指定相对于正在执行的文件位置的路径。
您可以使用获取该文件的路径__file__
,然后使用os.path
模块对其进行操作(请参见此答案)
对于您的情况,假设您main.ini
位于正在运行的脚本的父目录中,则可以执行
inifile = os.path.join(os.path.dirname(os.path.dirname(__file__)), "main.ini")
config.read(inifile)
您需要注意的另一件事是,实际检查ini文件是否已加载可能很有用。如果找不到该文件,它将仅返回一个空对象,因此您可以检查该文件并打印消息或错误。
希望这会有所帮助。其他链接的答案提供了有关这些想法的更多有用信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句