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]