python sys.path[0_[项目实践] python文件路径引用的规则,记一次使用sys.path[0]的问题,及如何区分 ../与 ./的使用场景...

本文通过一个实际的项目案例,讲解了Python中如何正确引用文件路径,特别是在使用`sys.path[0]`和相对路径`../`、`./`时的问题。当在不同目录层级调用文件时,了解这些路径引用的规则至关重要。文中通过目录结构示例,明确了在不同场景下选择`../`或`./`的原则:当目标文件位于执行文件的上一级目录时使用`../`,同级目录则使用`./`。
摘要由CSDN通过智能技术生成

下面是一个获取配置的代码

1 defgetValue(self,section,option):2 """

3 @file: string,the name of the config file4 @section: string,the name of the section in config file5 @option: string,the name of the option in section field6 This function will return a int value which the option is specified.7 """

8 try:9 configs =ConfigParser()10 filepath = sys.path[1] + "\\config\\" + self.filename + ".ini"

11 #print (filepath)

12 line =configs.read(filepath)13 result =configs.getint(section, option)14 returnint(result)15 exceptException as e:16 print (e)

在实际引用该段代码时,随着在其它模块中进行引用时,经常会发现提示模块不存在,为防止后面再出现该问题,将 filepath 这个进行优化,不采用 sys.path方法,改为如下:

1 defgetValue(self,section,option):2 """

3 @file: string,the name of the config file4 @section: string,the name of the s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值