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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3430372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:02:38  来源:igfitidea点击:

How do I get the full path of the current file's directory?

pythondirectory

提问by Shubham

I want to get the current file's directory path. I tried:

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

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

But how can I retrieve the directory's path?

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

For example:

例如:

'C:\python27\'

采纳答案by Bryan Oakley

Python 3

蟒蛇 3

For the directory of the script being run:

对于正在运行的脚本的目录:

import pathlib
pathlib.Path(__file__).parent.absolute()

For the current working directory:

对于当前工作目录:

import pathlib
pathlib.Path().absolute()

Python 2 and 3

Python 2 和 3

For the directory of the script being run:

对于正在运行的脚本的目录:

import os
os.path.dirname(os.path.abspath(__file__))

If you mean the current working directory:

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

import os
os.path.abspath(os.getcwd())

Note that before and after fileis two underscores, not just one.

请注意,before 和 afterfile是两个下划线,而不仅仅是一个。

Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.

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

References

参考

  1. pathlibin the python documentation.
  2. os.path 2.7, os.path 3.8
  3. os.getcwd 2.7, os.getcwd 3.8
  4. what does the __file__ variable mean/do?
  1. python 文档中的pathlib
  2. 操作系统路径 2.7,操作系统路径 3.8
  3. os.getcwd 2.7, os.getcwd 3.8
  4. __file__ 变量是什么意思/做什么?

回答by chefsmart

import os
print os.path.dirname(__file__)

回答by mulg0r

You can use osand os.pathlibrary easily as follows

您可以按如下方式轻松使用osos.path

import os
os.chdir(os.path.dirname(os.getcwd()))

os.path.dirnamereturns upper directory from current one. It lets us change to an upper level without passing any file argument and without knowing absolute path.

os.path.dirname从当前目录返回上层目录。它让我们在不传递任何文件参数和不知道绝对路径的情况下更改到更高级别。

回答by Nafeez Quraishi

IPythonhas a magic command %pwdto get the present working directory. It can be used in following way:

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

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwdcan be used directly as following:

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

present_working_directory = %pwd

回答by Qiao Zhang

To keep the migration consistency across platforms (macOS/Windows/Linux), try:

要保持跨平台(macOS/Windows/Linux)的迁移一致性,请尝试:

path = r'%s' % os.getcwd().replace('\','/')

回答by Ron Kalian

Using Pathis the recommended way since Python 3:

Path从 Python 3 开始,使用是推荐的方式:

from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())  

Documentation: pathlib

文档:路径库

Note: If using Jupyter Notebook, __file__doesn't return expected value, so Path().absolute()has to be used.

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

回答by Gil Allen

I have made a function to use when running python under IIS in CGI in order to get the current folder:

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

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

回答by Jerusalem Programmer

## IMPORT MODULES
import os

## CALCULATE FILEPATH VARIABLE
filepath = os.path.abspath('') ## ~ os.getcwd()
## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
## ..OR DIFFERENT IN SOME CIRCUMSTANCES

回答by Suyang Xu

System: MacOS

系统:MacOS

Version: Python 3.6 w/ Anaconda

版本:带有 Anaconda 的 Python 3.6

import os

rootpath = os.getcwd()

os.chdir(rootpath)

回答by Arminius

In Python 3.x I do:

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

from pathlib import Path

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

Explanation:

解释:

  • Path(__file__)is the path to the current file.
  • .parentgives you the directorythe file is in.
  • .absolute()gives you the full absolutepath to it.
  • Path(__file__)是当前文件的路径。
  • .parent给你文件所在的目录
  • .absolute()为您提供完整的绝对路径。

Using pathlibis the modern way to work with paths. If you need it as a string later for some reason, just do str(path).

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