如何在Python中获取当前文件目录的完整路径?

Shu*_*ham 677 python directory

我想获取当前文件的目录路径.
我试过了:

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
Run Code Online (Sandbox Code Playgroud)

但是如何检索目录的路径?例如:

'C:\\python27\\'
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 1411

如果您指的是正在运行的脚本的目录:

import os
os.path.dirname(os.path.abspath(__file__))
Run Code Online (Sandbox Code Playgroud)

如果您的意思是当前的工作目录:

import os
os.getcwd()
Run Code Online (Sandbox Code Playgroud)

请注意,之前和之后file是两个下划线,而不仅仅是一个.

另请注意,如果您以交互方式运行或从文件以外的其他内容加载代码(例如:数据库或在线资源),则__file__可能无法设置,因为没有"当前文件"的概念.上面的答案假设运行文件中的python脚本最常见的情况.

  • 如果您不想在Windows上发现奇怪的行为,那么abspath()是必需的,其中dirname(__ file__)可能返回一个空字符串! (42认同)
  • 我建议使用realpath而不是abspath来解析可能的符号链接. (9认同)
  • @ cph2117:这只有在脚本中运行时才有效.如果从交互式提示符运行,则没有`__file__`.\ (7认同)
  • 应该是os.path.dirname(os.path.abspath(os .__ file__))? (4认同)
  • @DrBailey:不,ActivePython没什么特别之处.`__file__`(注意它在单词的两边是两个下划线)是python的标准部分.例如,它在基于C的模块中不可用,但它应始终在python脚本中可用. (2认同)
  • 使用 Path.resolve 方法 (https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve) 而不是 Path.absolute 方法,该方法未记录。 (2认同)

Ron*_*ian 80

在Python 3中:

from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())  
Run Code Online (Sandbox Code Playgroud)

  • 我不得不做`Path(__ file __).parent`来获取包含该文件的文件夹 (15认同)
  • `Path(__file__)` 并不总是有效,例如,它在 Jupyter Notebook 中不起作用。`Path().absolute()` 解决了这个问题。 (3认同)

Arm*_*ius 34

在Python 3.x中,我这样做:

from pathlib import Path

path = Path(__file__).parent.absolute()
Run Code Online (Sandbox Code Playgroud)

说明:

  • Path(__file__) 是当前文件的路径。
  • .parent为您提供文件所在的目录
  • .absolute()给您完整的绝对路径。

使用pathlib是使用路径的现代方法。如果以后由于某种原因需要它作为字符串,只需执行str(path)

  • 自2019年起,这应该是公认的答案。答案中也可能提到一件事:可以立即在带有Path(__ file __)。parent.joinpath的Path对象中调用.open()。 ('some_file.txt')。open()作为f:` (3认同)

Aks*_*jan 10

尝试这个:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))
Run Code Online (Sandbox Code Playgroud)

  • 最佳答案。这是我通常获取当前脚本路径的方式,谢谢。 (2认同)

che*_*art 9

import os
print os.path.dirname(__file__)
Run Code Online (Sandbox Code Playgroud)

  • 对不起,但这个答案是不正确的,正确的答案是由Bryan`dirname(abspath(__ file__))制作的.请参阅评论了解详情 (21认同)
  • @sorin实际上在Python 3.6上它们都是相同的 (2认同)

Sun*_*ear 7

我发现以下命令返回 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}')
Run Code Online (Sandbox Code Playgroud)

评论 !!!!

  1. dir1并且dir2仅在运行位于当前工作目录中的脚本时才有效,但在任何其他情况下都会中断。
  2. 鉴于此Path(__file__).is_absolute(),在 dir3 中True使用该方法显得多余。.absolute()
  3. 最短的有效命令是 dir4

说明链接:.resolve().absolute()Path( file ).parent().absolute()


mul*_*g0r 6

您可以轻松使用osos.path库,如下所示

import os
os.chdir(os.path.dirname(os.getcwd()))
Run Code Online (Sandbox Code Playgroud)

os.path.dirname返回当前的目录.它允许我们在不通过任何文件参数且不知道绝对路径的情况下更改为较高级别.

  • 这不会给出当前_file_的目录.它返回当前工作目录的目录,该目录可能完全不同.您的建议仅在文件位于当前工作目录中时才有效. (7认同)

Arp*_*ini 6

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))
Run Code Online (Sandbox Code Playgroud)

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

绝对路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlibseaborn Part2

文件路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlibseaborn Part2\data\fuel_econ.csv

文件存在:真

isa目录:假

文件扩展名:.csv

  • 这是误导性的,绝对是 cwd 不是您的文件所在的位置。不保证相同。 (5认同)
  • ``Path()`` 是当前工作目录,而不是脚本的目录。这仅在脚本实际上位于当前工作目录中的少数情况下“有效”。 (3认同)

Mar*_*hke 5

为了jupyter notebooks

jupyter notebooks变量中__file__不可用。但是,内核working directory等于笔记本的位置。因此你可以使用

选项1

%cwd
Run Code Online (Sandbox Code Playgroud)

选项2

from pathlib import Path
Path.cwd()
Run Code Online (Sandbox Code Playgroud)

选项3

import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
Run Code Online (Sandbox Code Playgroud)

如果你调用你的笔记本,这会起作用

  • 通过jupyter notebook并手动导航到您的笔记本
  • 直接由jupyter notebook tmp2/Untitled.ipynb

信息:使用pathlib是在 python 3 中处理路径的面向对象(也是推荐的)方法。

感谢@bjmc 的评论,指出该解决方案实际上是在访问工作目录。