我正在运行一个例程,打开一个目录及其所有子目录,执行一些任务,然后使用panda输出到.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
并且该子目录很容易用CCD_ 1进行分类。然而,我想运行该目录,它使用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
我在这里看到了这个答案:获得当前目录中所有子目录的列表,但不确定如何将其集成到我的例程中。
try:
import glob
path = glob.glob(r'/users/directory/*')
dataframe['sub-directory']=[os.path.basename(i) for i in path]