Find current directory and file's directory [d

2018-12-31 08:02发布

In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?

15条回答
深知你不懂我心
2楼-- · 2018-12-31 08:40

If you're searching for the location of the currently executed script, you can use sys.argv[0] to get the full path.

查看更多
梦该遗忘
3楼-- · 2018-12-31 08:41

Answer to #1:

If you want the current directory, do this:

import os
os.getcwd()

If you want just any folder name and you have the path to that folder, do this:

def get_folder_name(folder):
    '''
    Returns the folder name, given a full folder path
    '''
    return folder.split(os.sep)[-1]

Answer to #2:

import os
print os.path.abspath(__file__)
查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 08:42

Pathlib can be used this way to get the directory containing current script :

import pathlib
filepath = pathlib.Path(__file__).resolve().parent
查看更多
登录 后发表回答