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

>>> 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 InteractiveShellEmbedip_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 Pathpath = 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 placedmypath = 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 methodfilePath = mypath/'data'/'fuel_econ.csv'print('File path : {}'.format(filePath))#To check if file present in that directory or NotisfileExist = filePath.exists()print('isfileExist : {}'.format(isfileExist))#To check if the path is a directory or a Fileisadirectory = filePath.is_dir()print('isadirectory : {}'.format(isadirectory))#To get the extension of the filefileExtension = 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()

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

  1. 如何从文件的完整路径获取目录?

    获取文件所在目录的最简单方法是什么? 我正在使用它来设置工作目录. string filename = @"C:\MyDirectory\MyFile.bat"; 在这个例子中,我 ...

  2. VB根据窗口标题获取应用程序完整路径

    新建工程,添加一个command按钮和一个textbox,然后将下面的代码copy到代码区,运行即可见到效果了 'Option Explicit Private Declare Function Fi ...

  3. 解决asp.net FileUpload控件无法获取完整路径的问题 - 无序修改浏览器参数

    尝试了很多办法,都不能获取到文件的完整路径 //string pName = Server.MapPath(this.FileUpload1.PostedFile.FileName); //获取项目服 ...

  4. 五种方法,教你如何在Mac上查看文件完整路径

    在MacOS上,Finder显示文件默认是不带路径展示的,你进入某个文件夹只会显示文件夹的名称而已,如下图: 那如何获取或者显示文件的完整路径呢?在MacOS中有五种方法可以显示文件完整路径. 第一种 ...

  5. 如何获取文件的完整路径?

    有没有一种简单的方法可以打印file.txt的完整路径? file.txt = /nfs/an/disks/jj/home/dir/file.txt <command> dir> & ...

  6. Bash脚本获取自身完整路径的可靠方法

    本文翻译自:Reliable way for a Bash script to get the full path to itself [duplicate] This question alread ...

  7. PHP获取URL完整路径及物理路径

    2019独角兽企业重金招聘Python工程师标准>>> PHP的预定义变量$_SERVER是一个包含头部(headers),路径信息及脚本位置的数组,数组的实体由web服务器创建. ...

  8. C++获取当前所有进程的完整路径

    实现代码 #include <stdio.h> #include <windows.h> #include <tlhelp32.h> #include <st ...

  9. ios 获取沙盒文件名_IOS获取各种文件目录路径的方法

    iphone沙箱模型有四个文件夹,分别是什么,永久数据存储一般放在什么位置,得到模拟器的路径的简单方式是什么. documents,tmp,app,Library. (NSHomeDirectory( ...

最新文章

  1. 关于Linux,你该读哪些书
  2. Spring 接收表单List集合数据
  3. 这四种情况下,才是考虑分库分表的时候!
  4. BZOJ 2731 Luogu P3219 [HNOI2012]三角形覆盖问题 (扫描线)
  5. qmoc文件_Qt中Q_OBJECT与生成的moc文件的作用
  6. Class.getResource和ClassLoader.getResource
  7. 微信小程序图片删除php,关于微信小程序中图片处理的问题总结
  8. 1.7编程基础之字符串 06 合法 C 标识符 python
  9. 《架构探险》第三章 项目核心实现
  10. spring boot demo( 获取一个RESTful web service)
  11. Django_modelform组件
  12. html 分割字符串,详解js常用分割取字符串的方法
  13. SQL server常见问题
  14. java webservice调用sap_java调用sap webservice
  15. CAD二次开发(C#)之添加文字样式
  16. 2017年IT人期末考试卷,能考60分就是自己人!
  17. 深入剖析Tomcat第一章ERR_INVALID_HTTP_RESPONSE
  18. Android源码编译(基于Ubuntu18.0.4)
  19. 有源晶振和无源晶振的比较
  20. 电商平台如何构建用户画像?

热门文章

  1. 深入剖析SolrCloud(四)
  2. 一个没暂时没有办法实现的问题和一个有意思的小问题!
  3. zabbix 搭建 mysql 连接报错
  4. iOS原生实现二维码拉近放大
  5. 挑战练习14.8 删除crime 记录
  6. Shell 字符串处理、获取文件名和后缀名
  7. Android开发学习之路-LruCache使用和源码分析
  8. 《软件需求最佳实践》——阅读笔记一
  9. C# 如何在空间运行时调整控件位置和大小
  10. CSS2.0样式手册_说明_SDK下载chm