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

这篇博客讨论了如何在Python中获取当前文件或脚本的目录路径。提到了多种方法,包括使用`os.path.abspath(__file__)`,`os.getcwd()`,以及`pathlib.Path.cwd()`等。还特别指出在不同环境如Jupyter Notebook中需要注意的差异,并提醒用户要确保跨平台兼容性。
摘要由CSDN通过智能技术生成

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

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

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

例如:

'C:\\python27\\'

#1楼

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

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

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


#2楼

如果您表示正在运行的脚本目录:

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

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

import os
os.getcwd()

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

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


#3楼

import os
print os.path.dirname(__file__)

#4楼

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

#5楼

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

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

#6楼

从Python 3开始,推荐使用Path

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

文档: pathlib

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


#7楼

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

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

#8楼

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

#9楼

系统:MacOS

版本:Python 3.6 w / Anaconda

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


#10楼

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

from pathlib import Path

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

说明:

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

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


#11楼

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:True

isadirectory:错误

文件扩展名:.csv


#12楼

尝试这个:

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

#13楼

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值