首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用glob将子目录输出到pandas .csv

使用glob将子目录输出到pandas .csv
EN

Stack Overflow用户
提问于 2021-01-06 16:57:00
回答 1查看 48关注 0票数 0

我正在运行一个例程,该例程打开一个目录及其所有子目录,执行一些任务,然后使用pandas输出到一个.csv。但是,我需要建立子目录名称,以便也可以将其输出到.csv。

访问单个子目录时,我可以使用以下命令:

代码语言:javascript
复制
path = r'/users/directory/sub-directory'
dataframe['sub-directory'] = os.path.basename(path)
print (dataframe)

A B C sub-directory
1 2 3 Folder-1
4 5 6 Folder-1
7 8 9 Folder-1

并且该子目录很容易与os.path.basename(path)相关联。但是,我想遍历目录,它使用Glob工作,但在输出到.csv时丢失了子目录名称:

代码语言:javascript
复制
path = r'/users/directory/*/' #Using Glob
dataframe['sub-directory'] = os.path.basename(path)
print (dataframe)

#Actual Output
A B C sub-directory
1 2 3 NaN
4 5 6 NaN
7 8 9 NaN
1 2 3 NaN
4 5 6 NaN
7 8 9 NaN

#Desired Output
A B C sub-directory
1 2 3 Folder-1
4 5 6 Folder-1
7 8 9 Folder-1
1 2 3 Folder-2
4 5 6 Folder-3
7 8 9 Folder 4

我在这里看到了这个答案:Getting a list of all subdirectories in the current directory,但不确定如何将其集成到我的例程中。

EN

回答 1

Stack Overflow用户

发布于 2021-01-06 17:06:13

尝试:

代码语言:javascript
复制
import glob

path = glob.glob(r'/users/directory/*')
dataframe['sub-directory']=[os.path.basename(i) for i in path]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65592828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档