如何解决使用 glob 将子目录输出到 pandas .csv
我正在运行一个例程,它打开一个目录及其所有子目录,执行一些任务,然后使用 Pandas 输出到 .csv。但是,我需要建立子目录名称,所以它也可以输出到.csv。
访问单个子目录,我可以这样做:
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 时我丢失了子目录名称:
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,但不确定如何将它整合到我的日常生活中。
解决方法
试试:
import glob
path = glob.glob(r'/users/directory/*')
dataframe['sub-directory']=[os.path.basename(i) for i in path]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。