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

posted @   Gloria_Chen  阅读(700)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示