如何获取当前文件的目录路径? 我试着:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
但我想:
'C:\\python27\\'
如何获取当前文件的目录路径? 我试着:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
但我想:
'C:\\python27\\'
当前回答
试试这个:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
其他回答
试试这个:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
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
从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()。
这可以在没有模块的情况下完成。
def get_path():
return (__file__.replace(f"<your script name>.py", ""))
print(get_path())
在Python 3中。x我喜欢:
from pathlib import Path
path = Path(__file__).parent.absolute()
解释:
Path(__file__)是当前文件的路径。 .parent给出文件所在的目录。 .absolute()给出了它的完整绝对路径。
使用pathlib是使用路径的现代方式。如果以后因为某些原因需要它作为字符串,只需执行str(path)。