回答編集履歴
2
行出力を深さ優先にしたコードを追記
answer
CHANGED
@@ -30,4 +30,50 @@
|
|
30
30
|
# 作った2次元リストをデータフレームにする
|
31
31
|
path_df = pd.DataFrame(pathlist)
|
32
32
|
print(path_df)
|
33
|
+
```
|
34
|
+
行出力を深さ優先にしたコード
|
35
|
+
```Python
|
36
|
+
import pandas as pd
|
37
|
+
import os
|
38
|
+
|
39
|
+
def make_pathlist(path):
|
40
|
+
pathlist = []
|
41
|
+
for curDir, dirs, files in os.walk(path):
|
42
|
+
dum = curDir.count('\') - org.count('\')
|
43
|
+
for a_dir in dirs:
|
44
|
+
pathlist.append([curDir] + [''] * dum + [a_dir])
|
45
|
+
for a_file in files:
|
46
|
+
pathlist.append([curDir] + [''] * dum + [a_file])
|
47
|
+
mx = max(len(s) for s in pathlist)
|
48
|
+
return [s + [''] * (mx - len(s)) for s in pathlist]
|
49
|
+
|
50
|
+
def conv_to_depthfirst(pathlist):
|
51
|
+
for i in range(len(pathlist)):
|
52
|
+
for j in range(1, len(pathlist[i])):
|
53
|
+
dir = os.path.join(pathlist[i][0], pathlist[i][j])
|
54
|
+
if pathlist[i][j] and os.path.isdir(dir):
|
55
|
+
zs = ze = 0
|
56
|
+
for k in range(i+1, len(pathlist)):
|
57
|
+
if pathlist[k][0].find(dir) >= 0:
|
58
|
+
if zs == 0:
|
59
|
+
zs = ze = k
|
60
|
+
else:
|
61
|
+
ze = k
|
62
|
+
else:
|
63
|
+
if zs > 0:
|
64
|
+
break
|
65
|
+
if zs > i + 1:
|
66
|
+
# zs ~ ze を i と i + 1 の間に挿入する
|
67
|
+
return conv_to_depthfirst(pathlist[0:i+1] + pathlist[zs:ze+1] + pathlist[i+1:zs] + pathlist[ze+1:])
|
68
|
+
return pathlist
|
69
|
+
|
70
|
+
org = path = os.getcwd()
|
71
|
+
print("working directory is" , path)
|
72
|
+
# ディレクトリ階層+中身 が各列に入る2次元リストを作る
|
73
|
+
pathlist = make_pathlist(path)
|
74
|
+
pathlist = conv_to_depthfirst(pathlist) # 深さ優先順に変換
|
75
|
+
|
76
|
+
# 作った2次元リストをデータフレームにする
|
77
|
+
path_df = pd.DataFrame(pathlist)
|
78
|
+
print(path_df)
|
33
79
|
```
|
1
コメント追加と code をスマートに改善
answer
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
提示されている実行結果から、環境は Windows と推定しています。
|
1
2
|
```Python
|
2
3
|
import pandas as pd
|
3
4
|
import os
|
@@ -15,7 +16,8 @@
|
|
15
16
|
for curDir, dirs, files in os.walk(path):
|
16
17
|
#leaf = curDir.split('/')
|
17
18
|
#pathlist.append(leaf)
|
18
|
-
dum = 0 if curDir == org else len(curDir[len(org)+1:].split('\'))
|
19
|
+
#dum = 0 if curDir == org else len(curDir[len(org)+1:].split('\'))
|
20
|
+
dum = curDir.count('\') - org.count('\') # コードを改善
|
19
21
|
for a_dir in dirs:
|
20
22
|
#pathlist.append(leaf + [a_dir])
|
21
23
|
pathlist.append([curDir] + [''] * dum + [a_dir])
|