回答編集履歴
2
glob\(\)の結果にbasename\(\)を使うように修正
test
CHANGED
@@ -1,26 +1,64 @@
|
|
1
1
|
`glob.glob()`で得られた結果を、リスト内包表記で加工するやり方です。
|
2
|
+
|
3
|
+
`data`ディレクトリの中は下記のようになっているという前提です。`dir.xlsx`はディレクトリです。
|
4
|
+
|
5
|
+
```
|
6
|
+
|
7
|
+
data
|
8
|
+
|
9
|
+
├── a.xlsx
|
10
|
+
|
11
|
+
├── b.xlsx
|
12
|
+
|
13
|
+
├── dir.xlsx
|
14
|
+
|
15
|
+
└── ~$a.xlsx
|
16
|
+
|
17
|
+
```
|
2
18
|
|
3
19
|
|
4
20
|
|
5
21
|
```python
|
6
22
|
|
7
|
-
|
23
|
+
# coding: UTF-8
|
8
|
-
|
9
|
-
# ['a.xlsx', 'b.xlsx', '~$a.xlsx', 'dir.xlsx']
|
10
24
|
|
11
25
|
|
12
26
|
|
13
|
-
|
27
|
+
import os
|
14
28
|
|
15
|
-
|
29
|
+
import glob
|
16
30
|
|
17
31
|
|
18
32
|
|
19
|
-
files
|
33
|
+
files = glob.glob('./data/*.xlsx') # dir.xlsxはディレクトリ
|
20
34
|
|
35
|
+
print(files)
|
36
|
+
|
21
|
-
# ['a.xlsx', '
|
37
|
+
# ['./data/b.xlsx', './data/~$a.xlsx', './data/dir.xlsx', './data/a.xlsx']
|
22
38
|
|
23
39
|
|
40
|
+
|
41
|
+
files2 = [os.path.basename(f) for f in files] # ファイル名のみを取得
|
42
|
+
|
43
|
+
print(files2)
|
44
|
+
|
45
|
+
# ['b.xlsx', '~$a.xlsx', 'dir.xlsx', 'a.xlsx']
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
files3 = [f for f in files2 if f[:2] != '~$'] # 一時ファイルを削除
|
50
|
+
|
51
|
+
print(files3)
|
52
|
+
|
53
|
+
# ['b.xlsx', 'dir.xlsx', 'a.xlsx']
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
files4 = [f for f in files3 if os.path.isdir(f) == False] # ディレクトリ(dir.xlsx)を削除
|
58
|
+
|
59
|
+
print(files4)
|
60
|
+
|
61
|
+
# ['b.xlsx', 'a.xlsx']
|
24
62
|
|
25
63
|
```
|
26
64
|
|
@@ -31,3 +69,11 @@
|
|
31
69
|
追記
|
32
70
|
|
33
71
|
`glob()`はディレクトリも取得してしまうとのご指摘を受けましたので、修正しました。
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
---
|
76
|
+
|
77
|
+
追記2
|
78
|
+
|
79
|
+
`glob(./data/*.xlsx)`は`data`ディレクトリを含むファイル名を返すとのご指摘を頂き、全体的に修正しました。
|
1
ディレクトリを除外するように修正
test
CHANGED
@@ -6,14 +6,28 @@
|
|
6
6
|
|
7
7
|
files = glob.glob('./data/*.xlsx')
|
8
8
|
|
9
|
-
# ['a.xlsx', 'b.xlsx', '~$a.xlsx']
|
9
|
+
# ['a.xlsx', 'b.xlsx', '~$a.xlsx', 'dir.xlsx']
|
10
10
|
|
11
11
|
|
12
12
|
|
13
13
|
files2 = [f for f in files if f[:2] != '~$']
|
14
|
+
|
15
|
+
# ['a.xlsx', 'b.xlsx', 'dir.xlsx']
|
16
|
+
|
17
|
+
|
18
|
+
|
19
|
+
files3 = [f for f in files2 if os.path.isdir(f) == False] # ディレクトリ"dir.xlsx"を除外
|
14
20
|
|
15
21
|
# ['a.xlsx', 'b.xlsx']
|
16
22
|
|
17
23
|
|
18
24
|
|
19
25
|
```
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
---
|
30
|
+
|
31
|
+
追記
|
32
|
+
|
33
|
+
`glob()`はディレクトリも取得してしまうとのご指摘を受けましたので、修正しました。
|