我正在运行一个例程,该例程打开一个目录及其所有子目录,执行一些任务,然后使用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,但不确定如何将其集成到我的例程中。
发布于 2021-01-06 17:06:13
尝试:
import glob
path = glob.glob(r'/users/directory/*')
dataframe['sub-directory']=[os.path.basename(i) for i in path]https://stackoverflow.com/questions/65592828
复制相似问题