質問するログイン新規登録

回答編集履歴

2

glob\(\)の結果にbasename\(\)を使うように修正

2017/09/10 08:12

投稿

tsuemura
tsuemura

スコア663

answer CHANGED
@@ -1,17 +1,40 @@
1
1
  `glob.glob()`で得られた結果を、リスト内包表記で加工するやり方です。
2
+ `data`ディレクトリの中は下記のようになっているという前提です。`dir.xlsx`はディレクトリです。
3
+ ```
4
+ data
5
+ ├── a.xlsx
6
+ ├── b.xlsx
7
+ ├── dir.xlsx
8
+ └── ~$a.xlsx
9
+ ```
2
10
 
3
11
  ```python
4
- files = glob.glob('./data/*.xlsx')
12
+ # coding: UTF-8
5
- # ['a.xlsx', 'b.xlsx', '~$a.xlsx', 'dir.xlsx']
6
13
 
14
+ import os
7
- files2 = [f for f in files if f[:2] != '~$']
15
+ import glob
8
- # ['a.xlsx', 'b.xlsx', 'dir.xlsx']
9
16
 
10
- files3 = [f for f in files2 if os.path.isdir(f) == False] # ディレクトリ"dir.xlsx"を除外
17
+ files = glob.glob('./data/*.xlsx') # dir.xlsxはディレクトリ
18
+ print(files)
11
- # ['a.xlsx', 'b.xlsx']
19
+ # ['./data/b.xlsx', './data/~$a.xlsx', './data/dir.xlsx', './data/a.xlsx']
12
20
 
21
+ files2 = [os.path.basename(f) for f in files] # ファイル名のみを取得
22
+ print(files2)
23
+ # ['b.xlsx', '~$a.xlsx', 'dir.xlsx', 'a.xlsx']
24
+
25
+ files3 = [f for f in files2 if f[:2] != '~$'] # 一時ファイルを削除
26
+ print(files3)
27
+ # ['b.xlsx', 'dir.xlsx', 'a.xlsx']
28
+
29
+ files4 = [f for f in files3 if os.path.isdir(f) == False] # ディレクトリ(dir.xlsx)を削除
30
+ print(files4)
31
+ # ['b.xlsx', 'a.xlsx']
13
32
  ```
14
33
 
15
34
  ---
16
35
  追記
17
- `glob()`はディレクトリも取得してしまうとのご指摘を受けましたので、修正しました。
36
+ `glob()`はディレクトリも取得してしまうとのご指摘を受けましたので、修正しました。
37
+
38
+ ---
39
+ 追記2
40
+ `glob(./data/*.xlsx)`は`data`ディレクトリを含むファイル名を返すとのご指摘を頂き、全体的に修正しました。

1

ディレクトリを除外するように修正

2017/09/10 08:12

投稿

tsuemura
tsuemura

スコア663

answer CHANGED
@@ -2,9 +2,16 @@
2
2
 
3
3
  ```python
4
4
  files = glob.glob('./data/*.xlsx')
5
- # ['a.xlsx', 'b.xlsx', '~$a.xlsx']
5
+ # ['a.xlsx', 'b.xlsx', '~$a.xlsx', 'dir.xlsx']
6
6
 
7
7
  files2 = [f for f in files if f[:2] != '~$']
8
+ # ['a.xlsx', 'b.xlsx', 'dir.xlsx']
9
+
10
+ files3 = [f for f in files2 if os.path.isdir(f) == False] # ディレクトリ"dir.xlsx"を除外
8
11
  # ['a.xlsx', 'b.xlsx']
9
12
 
10
- ```
13
+ ```
14
+
15
+ ---
16
+ 追記
17
+ `glob()`はディレクトリも取得してしまうとのご指摘を受けましたので、修正しました。