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

时间:2010-08-07 12:17:52

标签: python filesystems

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

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

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

'C:\\python27\\'

16 个答案:

答案 0 :(得分:1225)

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

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

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

import os
os.getcwd()

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

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

答案 1 :(得分:39)

在Python 3中:

from pathlib import Path

mypath = Path().absolute()
print(mypath)

pathlib

的文档

答案 2 :(得分:9)

import os
print os.path.dirname(__file__)

答案 3 :(得分:5)

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

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

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

答案 4 :(得分:3)

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

from pathlib import Path

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

说明:

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

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

答案 5 :(得分:1)

PYTHON中有用的路径属性:

(first data of NK - min column NK data) / (max column NK- min column NK) * 0.8 + 0.1

输出: 绝对路径是放置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

答案 6 :(得分:1)

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

import os
print(os.getcwd())

如果要更改当前工作目录

os.chdir(path)

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

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

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

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

答案 9 :(得分:0)

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

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

答案 10 :(得分:0)

系统:MacOS

版本:带有Anaconda的Python 3.6

import os rootpath = os.getcwd() os.chdir(rootpath)

答案 11 :(得分:0)

尝试一下:

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

答案 12 :(得分:0)

我发现以下命令将全部返回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()Path(file).parent().absolute()

答案 13 :(得分:0)

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

主要/ 折叠1 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 :(得分:0)

这就是我的工作

    path = os.getcwd().replace(os.sep, "/")
    name = Path(__file__).name
    full = str(path) + "/" + str(name)
    indv = full.split("/")

答案 15 :(得分:-1)

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