如何获取当前文件的目录路径? 我试着:

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'

但我想:

'C:\\python27\\'

当前回答

试试这个:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

其他回答

从Python 3开始,推荐使用pathlib中的Path:

from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__  

注意:如果使用Jupyter Notebook, __file__不会返回预期值,因此必须使用Path().absolute()。

试试这个:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

这可以在没有模块的情况下完成。

def get_path():
    return (__file__.replace(f"<your script name>.py", ""))
print(get_path())

也适用于__file__不可用的情况(jupyter笔记本)

import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)

还使用了pathlib,这是python 3中处理路径的面向对象的方式。

Python 2和3

你还可以简单地做:

from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)

输出如下:

C:\my_folder\sub_folder\