python 获取当前路径

  1. sys.argv[0]
    import sys
    print sys.argv[0]#获得的是当前执行脚本的位置(若在命令行执行的该命令,则为空)

    运行结果(在python脚本中执行的结果):

    F:/SEG/myResearch/myProject_2/test.py

  2. os模块
    import os
    print os.getcwd()#获得当前工作目录
    print os.path.abspath('.')#获得当前工作目录
    print os.path.abspath('..')#获得当前工作目录的父目录
    print os.path.abspath(os.curdir)#获得当前工作目录

    运行结果:

    F:\SEG\myResearch\myProject_2
    F:\SEG\myResearch\myProject_2
    F:\SEG\myResearch
    F:\SEG\myResearch\myProject_2

    注:argv[0]只是得到的是当前脚本的绝对位置;而os模块中的几种获得路径的方法,得到的是当前的工作目录,如:open('1.txt','r'),则会在当前工作目录查找该文件。即大部分的文件操作都是相对于当前工作路径。

  3. 若要改变当前工作路径,可以用:os.chdir(path) 。如os.chdir(E:\Program Files),则大部分的文件操作就会是相对于E:\dir1fobj = open('Hello.txt'),实际会打开E:\Program Files\Hello.txt文件。

猜你喜欢

转载自blog.csdn.net/ever_peng/article/details/80066778