python中的绝对路径和相对路径

绝对路径的三种写法:

方法1,

with open(rC:\Git\moxyrulesnewui_python\org\adv\rules\UIAutomation\testcase\test.py) as file_obj:

    contents = file_obj.read()

    print(contents.strip)

方法2,

with open(C:\\Git\\moxyrulesnewui_python1\\org\\adv\\rules\\UIAutomation\\testcase\\test.py) as file_obj:

    contents = file_obj.read()

    print(contents.strip)

方法3

with open(C:/Git/moxyrulesnewui_python/org/adv/rules/UIAutomation/testcase/test.py) as file_obj:

    contents = file_obj.read()

    print(contents.strip)

相对路径:

import os

import sys

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__File__)))

sys.path.insert(0, BASE_DIR)

with open(test.py) as file_obj:

    contents = file_obj.read()

    print(contents.strip)

 

利用以上四种方法可以解决错误: FileNotFoundError: [Errno 2] No such file or directory,ModuleNotFoundError: No module named xxx