glob.glob jpg png
时间: 2023-10-31 11:59:51 浏览: 248
glob.glob函数是一个用于获取文件路径的函数,可以通过指定的模式匹配来获取文件路径。对于文件类型的筛选,可以使用通配符来指定不同的文件类型。
对于获取指定目录下的所有jpg文件的话,可以使用如下代码:
```python
import glob
jpg_files = glob.glob("/path/to/directory/*.jpg")
```
这段代码中的`/path/to/directory/`需要替换为你要获取jpg文件的目录路径。
同样的,如果想获取指定目录下的所有png文件,可以使用如下代码:
```python
import glob
png_files = glob.glob("/path/to/directory/*.png")
```
这段代码中的`/path/to/directory/`同样需要替换为你要获取png文件的目录路径。
所以,根据你提供的引用内容和,可以看出可以使用`glob.glob`函数来获取指定目录下的jpg和png文件。
相关问题
else: self.images = glob.glob(os.path.join(filepath, '*.png')) + \ glob.glob(os.path.join(filepath, '*.jpg')) + \ glob.glob(os.path.join(filepath, '*.ppm')) self.images.sort() self.N = len(self.images) logging.info(f'Loading {self.N} images') self.mode = 'images' else: raise IOError('Error filepath (camerax/path of images/path of videos): ', filepath)
这段代码是在上一个条件分支语句中的 `elif` 分支内,当 `filepath` 不是相机编号且存在于文件系统中,但不是一个文件时,会执行其后面的代码。它首先使用 `glob.glob()` 函数查找指定目录下所有扩展名为 `.png`、`.jpg` 和 `.ppm` 的文件,并将它们的路径存储在类属性 `self.images` 中。然后,它对这些路径进行排序并将文件总数赋值给类属性 `self.N`。接下来,它打印一些有关加载图像的信息,并将类属性 `self.mode` 设置为 `'images'`,表示当前模式为图像模式。如果 `filepath` 既不是相机编号,也不是一个文件夹,则会引发 `IOError` 异常,异常消息中将指出错误的路径。
举几个例glob.glob{....}
以下是几个使用 glob.glob 函数的例子:
1. 匹配所有以 ".txt" 结尾的文件名:
```python
import glob
files = glob.glob("*.txt")
print(files)
```
2. 匹配所有以 "file" 开头,后面跟着一个数字,最后以 ".csv" 结尾的文件名:
```python
import glob
files = glob.glob("file[0-9].csv")
print(files)
```
3. 匹配所有以 "a" 或 "b" 开头,后面跟着一个数字,最后以 ".png" 或 ".jpg" 结尾的文件名:
```python
import glob
files = glob.glob("[ab][0-9]*.[pj][ng]")
print(files)
```
4. 匹配所有以 "2021" 开头,后面跟着一个数字,最后以 ".xlsx" 或 ".xls" 结尾的文件名:
```python
import glob
files = glob.glob("2021[0-9]*.[x][l][s][x]")
print(files)
```
注意,在使用匹配模式时,需要根据具体情况选择合适的模式来匹配文件名,以避免不必要的匹配错误。
阅读全文
相关推荐















