[英]How do I get the full path of the current file's directory?
如何获取当前文件的目录路径? 我试过了:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
但是我想要:
'C:\\python27\\'
特殊变量__file__
包含当前文件的路径。 从中我们可以使用pathlib
或os.path
模块获取目录。
对于正在运行的脚本的目录:
import pathlib
pathlib.Path(__file__).parent.resolve()
对于当前工作目录:
import pathlib
pathlib.Path().resolve()
对于正在运行的脚本的目录:
import os
os.path.dirname(os.path.abspath(__file__))
如果您的意思是当前工作目录:
import os
os.path.abspath(os.getcwd())
请注意, file
前后是两个下划线,而不仅仅是一个。
另请注意,如果您以交互方式运行或从文件以外的其他内容(例如:数据库或在线资源)加载代码,则可能不会设置__file__
,因为没有“当前文件”的概念。 上面的答案假设最常见的情况是运行文件中的 python 脚本。
自 Python 3 以来,推荐使用pathlib
中的Path
:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
注意:如果使用 Jupyter Notebook,__ __file__
不会返回预期值,因此必须使用Path().absolute()
。
在 Python 3.x 中,我这样做:
from pathlib import Path
path = Path(__file__).parent.absolute()
解释:
Path(__file__)
是当前文件的路径。.parent
为您提供文件所在的目录。.absolute()
为您提供完整的绝对路径。 使用pathlib
是使用路径的现代方式。 如果您稍后出于某种原因需要它作为字符串,只需执行str(path)
。
尝试这个:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print(os.path.dirname(__file__))
我发现以下命令返回 Python 3 脚本的父目录的完整路径。
Python 3 脚本:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 and above 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
dir4 = Path(__file__).parent
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')
评论 !!!!
dir1
和dir2
仅在运行位于当前工作目录中的脚本时有效,但在任何其他情况下都会中断。Path(__file__).is_absolute()
是True
,在 dir3 中使用.absolute()
方法似乎是多余的。解释链接: .resolve() , .absolute() , Path( file ).parent().absolute()
您可以轻松使用os
和os.path
库,如下所示
import os
os.chdir(os.path.dirname(os.getcwd()))
os.path.dirname
从当前目录返回上层目录。 它让我们在不传递任何文件参数和不知道绝对路径的情况下更改到更高级别。
os.path.dirname(os.path.abspath(myfilename))
要保持跨平台(macOS/Windows/Linux)的迁移一致性,请尝试:
path = r'%s' % os.getcwd().replace('\\','/')
## 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
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 : 真
isa 目录:错误
文件扩展名:.csv
假设您有以下目录结构:-
主要/ 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)
__file__
不可用(jupyter notebooks)也可以工作import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
还使用pathlib ,这是 python 3 中面向 object 处理路径的方式。
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
为了获取当前文件夹,我在 CGI 中的 IIS 下运行 python 时创建了一个函数:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
return path[len(path)-1]
如果只想查看当前工作目录
import os
print(os.getcwd())
如果要更改当前工作目录
os.chdir(path)
path 是一个字符串,包含要移动的所需路径。 例如
path = "C:\\Users\\xyz\\Desktop\\move here"
这就是我的工作
path = os.getcwd().replace(os.sep, "/")
name = Path(__file__).name
full = str(path) + "/" + str(name)
indv = full.split("/")
您也可以简单地执行以下操作:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
输出如下:
C:\my_folder\sub_folder\
这可以在没有模块的情况下完成。
def get_path():
return (__file__.replace(f"<your script name>.py", ""))
print(get_path())
系统:MacOS
版本:带有 Anaconda 的 Python 3.6
import os
rootpath = os.getcwd()
os.chdir(rootpath)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.