如何获取当前文件的目录路径? 我试着:

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'

但我想:

'C:\\python27\\'

当前回答

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

其他回答

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.path.dirname(__file__))

python中有用的路径属性:

from pathlib import Path

#Returns the path of the current directory
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 and seaborn Part2\data\ fuel_econc .csv

isfileExist: True

isadirectory: False

文件扩展名:.csv

Python 2和3

你还可以简单地做:

from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)

输出如下:

C:\my_folder\sub_folder\