我想获取当前文件的目录路径。 我试过了:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
但是如何检索目录的路径?
例如:
'C:\\python27\\'
#1楼
您可以如下轻松使用os
和os.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()