如何获取当前文件的目录路径?我尝试了:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
但我想要:
'C:\\python27\\'
特殊变量 __file__
包含当前文件的路径。通过使用 pathlib
或 os.path
模块,我们可以获取该目录。
对于正在运行的脚本所在的目录:
import pathlib
pathlib.Path(__file__).parent.resolve()
对于当前工作目录:
import pathlib
pathlib.Path().resolve()
对于正在运行的脚本所在的目录:
import os
os.path.dirname(os.path.abspath(__file__))
import os
os.path.abspath(os.getcwd())
file
之前和之后都有两个下划线,而不是一个。__file__
可能未设置。上述答案假定最常见的情况是运行在文件中的Python脚本。
__file__
(请注意它两边都有两个下划线)是Python的标准组成部分。例如在基于C的模块中就无法使用它,但在Python脚本中它应该总是可用的。 - Bryan Oakley使用自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()
。
Path(__file__).parent
来获取包含该文件的文件夹。 - YellowPillowPath().absolute()
,并且您正在从位于“path/to/script”的某个脚本中调用该模块,则会返回path/to/script
而不是path/to/module
。 - YellowPillowPath(__file__).cwd()
更加明确。 - C.W.Path(__file__)
并不总是有效,例如在 Jupyter Notebook 中它无法正常工作。Path().absolute()
可以解决这个问题。 - Ron KalianPath(__file__)
在 IDLE 中可以正常工作,但是当我在命令行中执行的 Python 脚本中使用它时,它只会返回脚本的名称而不包括其父级路径...很奇怪...这是一个 bug 吗?我不得不使用 Path(__file__).absolute()
,就像你提到的那样,才能显示完整路径。发生在 Python 3.6 中。顺便说一下,在 Python3.6 文档中我没有找到 .absolute()
方法的描述。 - Sun Bearfrom pathlib import Path
path = Path(__file__).parent.absolute()
解释:
Path(__file__)
是当前文件的路径。.parent
给出了文件所在的目录。.absolute()
给出了它的完整绝对路径。使用pathlib
是处理路径的现代方法。如果以后需要将其作为字符串使用,请使用str(path)
。
Path
对象上调用.open()
,例如with Path(__file__).parent.joinpath('some_file.txt').open() as f:
。 - stefanct试一试:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print(os.path.dirname(__file__))
dirname(abspath(__file__))
。有关详细信息,请参阅评论。 - sorin/
。 - Abhishek Tripathi我发现以下命令可以返回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()
方法显得多余。Path()
不会 提供脚本/模块目录。它等同于 Path('.')
- 当前工作 目录。只有当在当前工作目录中运行脚本时才有效,但在任何其他情况下都会出错。 - MisterMiyagi__file__
不可用(jupyter笔记本),也可以正常工作import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
此外还使用了pathlib,它是Python 3中处理路径的面向对象方式。
sys.path[0]
包含了Python解释器的当前工作目录,而不是Python源代码文件所在的目录。详见:https://docs.python.org/3/library/sys.html#sys.path - undefinedPython中有用的路径属性:
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
和 seaborn Part2\data\fuel_econ.csv
文件是否存在:True
是否为目录:False
文件扩展名:.csv
Path()
是当前工作目录,而非脚本所在的目录。这仅在脚本确实位于当前工作目录的少数情况下才“有效”。 - MisterMiyagi你也可以简单地这么做:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
输出结果类似于:
C:\my_folder\sub_folder\
python3.8.10
的Windows 7
机器上,由于某种原因,__file__
似乎并没有返回任何路径,而只有文件名。只是提醒其他人注意一下... - Giorgos XouIPython
有一个魔法命令%pwd
,可以获取当前工作目录。它可以按以下方式使用:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
%pwd
,如下所示:present_working_directory = %pwd
NameError
错误,至少在Python 2.7.3版本上会出现这个问题,其他版本也可能会有此问题。 - drevicko