python get current path

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

    Running result (result executed in python script):

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

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

    operation result:

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

    Note: argv[0] only gets the absolute position of the current script; and several methods in the os module to get the path get the current working directory, such as: open('1.txt','r'), the file will be searched in the current working directory. That is, most file operations are relative to the current working path.

  3. To change the current working path, use: os.chdir(path) . For example os.chdir(E:\Program Files), most file operations will be relative to E:\dir1. fobj = open('Hello.txt'), which will actually open the E:\Program Files\Hello.txtfile.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324780960&siteId=291194637