Skip to content

Commit

Permalink
glob 文件查找
Browse files Browse the repository at this point in the history
  • Loading branch information
王奇文 committed Sep 22, 2024
1 parent 8a3e09b commit 57dc510
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions _posts/2019-06-30-python.md
Original file line number Diff line number Diff line change
Expand Up @@ -4098,6 +4098,13 @@ p.suffix # 获取path文件后缀

### 遍历文件

分情形
- 只有文件时,用 `os.listdir`
- 包含目录时,用 `os.walk`
- 通配符查找, 用 glob

#### os.listdir/walk

分情形
- 只有文件时,用 `os.listdir`
- 包含目录时,用 `os.walk`
Expand All @@ -4115,6 +4122,94 @@ for filepath,dirnames,filenames in os.walk(path):
print(os.path.join(filepath,filename))
```

#### glob

glob 是 python 自带的**操作文件**模块。
- glob 查找符合规定的文件路径名

常用的方法有 `glob.glob()``glob.iglob()`
- `glob.glob()` 返回一个**列表**
- `glob.iglob()` 返回**生成器**

**通配符**`正则表达式`(re 模块)不同。
- `*` 匹配0个或多个字符;
- `**` 匹配所有文件,目录,子目录和子目录里面的文件 (3.5版本新增)
- `?` 匹配单个字符;
- `[]` 匹配指定范围内的字符,如:`[0-9]`匹配数字。
- `[!]` 匹配不在指定范围内的字符

```py
import glob

for name in glob.glob('dir/*'):
print(name)
```

示例目录
- 当前目录只有两个文件, 其余都是目录

```
.
├── example
├── dir1
├── dir2
├── dir3
├── train
├── val
├── test
├── _config.yml
└── exp.py
```


遍历**当前**目录

```py
print(glob.glob('./*'))
# out:
# ['.\\example', '.\\exp.py', '.\\test', '.\\train', '.\\val', '.\\_config.yml']
```

遍历**上一级**目录(example文件夹中)

```py
print(glob.glob('../*'))
# out:
# ['.\\example', '.\\exp.py', '.\\test', '.\\train', '.\\val', '.\\_config.yml']
```

遍历本级下文件

```py
print(glob.glob('./*.*')) #本级下所有文件
print(glob.glob("./*.yml")) #本级下所有yml文件
# out:
# ['.\\exp.py', '.\\_config.yml']
# ['.\\_config.yml']
```

匹配特定文件目录

```py
print(glob.glob("./*[ca][nf]*")) # 匹配ca和nf字母组合但一定相邻的名字
print(glob.glob("./*[ca]*[nf]*")) # 匹配有ca和nf中任意字母组合的名字
print(glob.glob("./*e?p*")) # 匹配e和p中间只有一个字符的名字
# out:
# []
# ['.\\train', '.\\_config.yml']
# ['.\\exp.py']
```

匹配子目录及文件

```py
print(glob.glob("./example/*")) # 遍历example文件夹中所有内容
print(glob.glob("./example/*/*")) # 遍历example文件夹中所有子文件夹及子文件夹中的文件
# out:
# ['./example\\dir1', './example\\dir2', './example\\dir3']
# ['./example\\dir1\\dir1.py', './example\\dir2\\dir2.py', './example\\dir3\\dir3.py']
```


## 正则表达式

Expand Down

0 comments on commit 57dc510

Please sign in to comment.