Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取目录名_Python_Os.walk - Fatal编程技术网

Python 获取目录名

Python 获取目录名,python,os.walk,Python,Os.walk,我有这样的文件结构: d:\temp\random1\index.html d:\temp\random2\index.html d:\temp\random3\index.html 我想用python获取列表的路径。因此,输出将是: files = ['path': 'd:\temp\random1\index.html', 'directory': 'random1'] 我正在使用这样的代码: files = [] for dirpath, dirnames, filenames in

我有这样的文件结构:

d:\temp\random1\index.html
d:\temp\random2\index.html
d:\temp\random3\index.html
我想用python获取列表的路径。因此,输出将是:

files = ['path': 'd:\temp\random1\index.html', 'directory': 'random1']
我正在使用这样的代码:

files = []
for dirpath, dirnames, filenames in os.walk('D:\\temp'):
    for fname in filenames:
        if fname.endswith(".md"):
            path = os.path.join(dirpath,fname)
            files.append({'path':path,'directory': dirpath})
但我不知道如何获取目录值。使用此代码得到的结果是:

files = ['path': 'd:\temp\random1\index.html', 'directory': 'd:\temp\random1\']
如何在没有恶意攻击的情况下获取目录?

试试看

dirname = dirpath.split(os.path.sep)[-1]