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

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

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

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

例如:

'C:\\python27\\'

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\\'

回答 0

Python 3

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

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

对于当前工作目录:

import pathlib
pathlib.Path().absolute()

Python 2和3

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

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

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

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

请注意,前后分别file是两个下划线,而不仅仅是一个。

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

参考文献

  1. python文档中的pathlib
  2. os.path 2.7os.path 3.8
  3. os.getcwd 2.7os.getcwd 3.8
  4. __file__变量的含义/作用是什么?

Python 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

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 file is two underscores, not just one.

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.

References

  1. pathlib in 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

使用Path是因为Python 3的推荐方式:

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

文档:pathlib

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

Using Path is the recommended way since 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.


回答 2

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

from pathlib import Path

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

说明:

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

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

In Python 3.x I do:

from pathlib import Path

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

Explanation:

  • Path(__file__) is the path to the current file.
  • .parent gives you the directory the file is in.
  • .absolute() gives you the full absolute path to it.

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


回答 3

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

回答 4

您可以轻松地使用os和存储os.path库,如下所示

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

os.path.dirname从当前目录返回上一级目录。它使我们可以在不传递任何文件参数且不知道绝对路径的情况下切换到更高级别。

You can use os and os.path library easily as follows

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

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


回答 5

尝试这个:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

Try this:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

回答 6

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

Python 3.6脚本:

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

from pathlib import Path

#Get the absolute path of a Python3.6 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 

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

说明链接:.resolve() .absolute() 路径(文件).parent()绝对的()。

I found the following commands will all return the full path of the parent directory of a Python 3.6 script.

Python 3.6 Script:

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

from pathlib import Path

#Get the absolute path of a Python3.6 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 

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

Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()


回答 7

系统:MacOS

版本:Python 3.6 w / Anaconda

import os

rootpath = os.getcwd()

os.chdir(rootpath)

System: MacOS

Version: Python 3.6 w/ Anaconda

import os

rootpath = os.getcwd()

os.chdir(rootpath)

回答 8

PYTHON中的有用路径属性:

 from pathlib import Path

    #Returns the path of the directory, where your script file is placed
    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

isfileExist:真

isadirectory:错误

文件扩展名:.csv

USEFUL PATH PROPERTIES IN PYTHON:

 from pathlib import Path

    #Returns the path of the directory, where your script file is placed
    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))

OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED

Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2

File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv

isfileExist : True

isadirectory : False

File extension : .csv


回答 9

如果您只想查看当前的工作目录

import os
print(os.getcwd)

如果要更改当前工作目录

os.chdir(path)

path是一个字符串,其中包含要移动的所需路径。例如

path = "C:\\Users\\xyz\\Desktop\\move here"

If you just want to see the current working directory

import os
print(os.getcwd)

If you want to change the current working directory

os.chdir(path)

path is a string containing the required path to be moved. e.g.

path = "C:\\Users\\xyz\\Desktop\\move here"

回答 10

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

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

回答 11

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

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

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

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

回答 12

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

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

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

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

回答 13

假设您具有以下目录结构:-

主/折1折2折3 …

folders = glob.glob("main/fold*")

for fold in folders:
    abspath = os.path.dirname(os.path.abspath(fold))
    fullpath = os.path.join(abspath, sch)
    print(fullpath)

Let’s assume you have the following directory structure: –

main/ fold1 fold2 fold3…

folders = glob.glob("main/fold*")

for fold in folders:
    abspath = os.path.dirname(os.path.abspath(fold))
    fullpath = os.path.join(abspath, sch)
    print(fullpath)

回答 14

## 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
## 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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。