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

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

但我想:

'C:\\python27\\'

当前回答

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

其他回答

python中有用的路径属性:

from pathlib import Path

#Returns the path of the current directory
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))

#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))

#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))

#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))

#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))

输出: 绝对路径是放置python文件的路径

绝对路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib和seaborn Part2

文件路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\ fuel_econc .csv

isfileExist: True

isadirectory: False

文件扩展名:.csv

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

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

在Python 3中。x我喜欢:

from pathlib import Path

path = Path(__file__).parent.absolute()

解释:

Path(__file__)是当前文件的路径。 .parent给出文件所在的目录。 .absolute()给出了它的完整绝对路径。

使用pathlib是使用路径的现代方式。如果以后因为某些原因需要它作为字符串,只需执行str(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()

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