美文网首页
python获取文件路径

python获取文件路径

作者: 草木山川 | 来源:发表于2022-02-22 13:28 被阅读0次
    # 获取文件的绝对路径
    os.path.realpath(__file__)
    # 获取文件所在的目录
    os.path.dirname(__file__)
    
    import pymysql
    import os, sys
    import configparser
    
    
    # os.path.dirname(__file__)返回当前脚本的路径
    BASE_PATH = os.path.dirname(os.path.dirname(__file__))
    # print(sys.path)
    # 添加目录
    # sys.path.append(BASE_PATH)
    # print(sys.path)
    print("---------------")
    print("返回当前脚本所在目录的上一级目录:"+BASE_PATH)
    data_file_path = os.path.join(BASE_PATH, "config", "settings.ini")
    print(data_file_path)
    # 使用ConfigParser获取ini文件
    cf = configparser.ConfigParser()
    # read()读文件内容
    cf.read(data_file_path, encoding='UTF-8')
    # get()为指定的section获取一个选项值
    host = cf.get("mysql", "mysql_host")
    port = cf.get("mysql", "mysql_port")
    user = cf.get("mysql", "mysql_user")
    password = cf.get("mysql", "mysql_password")
    db = cf.get("mysql", "mysql_db")
    print(host, port, user, password, db)
    
    BASE_PATH1 = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    print("---------------")
    print(os.path.realpath(__file__))
    print(BASE_PATH1)
    

    相关文章

      网友评论

          本文标题:python获取文件路径

          本文链接:https://www.haomeiwen.com/subject/trfahrtx.html