编程语言
首页 > 编程语言> > python中的绝对路径和相对路径

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

作者:互联网

绝对路径的三种写法:

方法1,

with open(r"C:\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

标签:obj,python,py,绝对路径,相对路径,file,strip,open,contents
来源: https://www.cnblogs.com/GlCh/p/16240528.html