Python 如何获取当前文件的完整路径';s目录?
我想获取当前文件的目录路径。 我试过: 但是如何检索目录的路径呢 例如:Python 如何获取当前文件的完整路径';s目录?,python,directory,Python,Directory,我想获取当前文件的目录路径。 我试过: 但是如何检索目录的路径呢 例如: 'C:\\python27\\' Python 3 对于正在运行的脚本的目录: import pathlib pathlib.Path(__file__).parent.absolute() import os os.path.dirname(os.path.abspath(__file__)) 对于当前工作目录: import pathlib pathlib.Path().absolute() import os
'C:\\python27\\'
Python 3
对于正在运行的脚本的目录:
import pathlib
pathlib.Path(__file__).parent.absolute()
import os
os.path.dirname(os.path.abspath(__file__))
对于当前工作目录:
import pathlib
pathlib.Path().absolute()
import os
os.path.abspath(os.getcwd())
Python 2和3
对于正在运行的脚本的目录:
import pathlib
pathlib.Path(__file__).parent.absolute()
import os
os.path.dirname(os.path.abspath(__file__))
如果您指的是当前工作目录:
import pathlib
pathlib.Path().absolute()
import os
os.path.abspath(os.getcwd())
请注意,文件
前后是两个下划线,而不仅仅是一个
另外请注意,如果您正在以交互方式运行或从文件以外的其他地方加载代码(例如:数据库或联机资源),\uuuu file\uuuu
可能不会被设置,因为没有“当前文件”的概念。上面的答案假设最常见的场景是运行文件中的python脚本
工具书类
您可以使用
os
和os.path
库,如下所示
import os
os.chdir(os.path.dirname(os.getcwd()))
os.path.dirname
从当前目录返回上层目录。
它允许我们在不传递任何文件参数和不知道绝对路径的情况下切换到更高级别
os.path.dirname(os.path.abspath(myfilename))
IPython
有一个神奇的命令%pwd
来获取当前的工作目录。可按以下方式使用:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
在IPython Jupyter笔记本电脑上,%pwd
可直接使用,如下所示:
present_working_directory = %pwd
要保持跨平台(macOS/Windows/Linux)迁移的一致性,请尝试:
使用
Path
是自Python 3以来的推荐方法:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
文件:
注意:如果使用Jupyter笔记本,
\uuuu file\uuuu
不会返回预期值,因此必须使用Path().absolute()
。为了获得当前文件夹,我在CGI中的IIS下运行python时使用了一个函数:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split('\\')
return path[len(path)-1]
系统:MacOS
版本:Python 3.6 w/Anaconda
import os
rootpath = os.getcwd()
os.chdir(rootpath)
在Python 3.x中,我执行以下操作:
from pathlib import Path
path = Path(__file__).parent.absolute()
说明:
是当前文件的路径Path(_文件)
提供文件所在的目录.parent
提供了它的完整绝对路径.absolute()
使用
pathlib
是处理路径的现代方法。如果以后出于某种原因需要它作为字符串,只需执行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\u Scripts\Matplotlib和seaborn Part2
文件路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity\u Scripts\Matplotlib和seaborn Part2\data\fuel\u econ.csv
isfileExist:True
ISA目录:False
文件扩展名:.csv请尝试以下操作:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
我发现以下命令都将返回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}')
解释链接:,假设您具有以下目录结构:- main/ 折叠1 折叠2 折叠3…
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)
如果您只想查看当前的工作目录
import os
print(os.getcwd())
os.chdir(path)
如果要更改当前工作目录
import os
print(os.getcwd())
os.chdir(path)
path是一个字符串,包含要移动的所需路径。
e、 g
如果您不想在windows上发现奇怪的行为,则必须使用abspath(),其中dirname(文件)可能返回空字符串!应该是os.path.dirname(os.path.abspath(os.\uu文件\uu))?@DrBailey:不,ActivePython没有什么特别之处<代码>\uuuu文件\uuuu(请注意,单词两边都有两个下划线)是python的标准部分。例如,它在基于C的模块中不可用,但在python脚本中应该始终可用。我建议使用realpath而不是abspath来解析可能的符号链接。@cph2117:只有在脚本中运行它时,这才有效。如果从交互式提示符运行,则没有
\uuuuuuu文件
\抱歉,这个答案不正确,正确的答案是由Bryan`dirname(abspath(file))做出的。有关详细信息,请参见注释。它将给出以下内容output@sorin实际上,在Python3.6上,它们都是\uuu文件的相同副本。当您将Python作为交互式shell运行时,没有定义
。你问题中的第一段代码看起来像是来自一个交互式shell,但实际上会产生一个namererror
,至少在Python2.7.3上是这样,但我猜其他代码也是这样。为什么。是这所以很难。关于这个话题有十几条线索。Python:“简单比复杂好……应该有一种——最好只有一种——显而易见的方法来实现。”这并没有给出当前文件的目录。它返回当前工作目录的目录,该目录可能完全不同。只有当文件在当前工作目录中时,您的建议才有效。@BryanOakley如果您返回cwd(),会有很多错误答案。这个问题不是关于IPython@Kiro,我的解决方案使用IPython回答问题。例如,如果有人用使用新库的解决方案回答问题,那么它是否仍然是问题的相关答案。@NafeezQuraishi您的解决方案引入了第三方库,以及一个类,您必须从中实例化才能获得所需的结果。我自己,以及我认为许多其他人出于一些原因试图避免使用外部库,我只会在其他方法都不起作用的情况下尝试您的解决方案。幸运的是,您可以使用一系列内置函数来获得所需的结果,而无需外部库。@elli0t,部分同意。考虑到使用Juyter笔记本电脑的人有这个问题,也许对于使用%PVD魔法命令来说,在OS输入上更容易和更好。@ NafeezQuraishi:我不知道你的意思。这个问题显然是在询问通往t的道路