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

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

但我想:

'C:\\python27\\'

当前回答

我做了一个函数,当在CGI中运行IIS下的python时,为了获得当前文件夹:

import os 
def getLocalFolder():
    path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
    return path[len(path)-1]

其他回答

从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()。

IPython有一个神奇的命令%pwd来获取当前的工作目录。它可以在以下方面使用:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

在IPython上Jupyter Notebook %pwd可以直接使用如下:

present_working_directory = %pwd

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

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

我发现以下命令返回Python 3脚本父目录的完整路径。

Python 3脚本:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from pathlib import Path

#Get the absolute path of a Python3.6 and above script.
dir1 = Path().resolve()  #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer 
dir3 = Path(__file__).parent.absolute() #See @Arminius answer
dir4 = Path(__file__).parent 

print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')

讲话! !

Dir1和dir2仅在运行位于当前工作目录中的脚本时有效,但在任何其他情况下都将中断。 假设Path(__file__).is_absolute()为True,在dir3中使用.absolute()方法显得多余。 最短的命令是dir4。

解释链接:.resolve(), .absolute(), Path(file).parent().absolute()

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

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

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