python如何读取目录中所有图片
时间: 2023-02-09 08:05:49 浏览: 62
在 Python 中,可以使用 os 模块来读取目录中的所有图片。
示例代码如下:
```
import os
path = './images' # 指定目录
for file in os.listdir(path):
if file.endswith('.jpg') or file.endswith('.png'): # 指定图片格式
print(file)
```
这段代码会打印出目录下所有以 .jpg 或 .png 结尾的文件名.
如果你想读取所有格式的图片,可以去掉if语句。
如果你想读取其它格式的文件,可以在if语句中添加文件后缀。
如果你想读取不止一个文件夹中的图片,可以在上述的代码中循环枚举多个目录,在循环中调用上面的代码即可.
相关问题
python 读取文件夹中所有图片
要读取文件夹中的所有图片文件,你可以使用Python的`os`和`PIL`库。下面是一个示例代码,演示了如何读取文件夹中的所有图片文件:
```python
import os
from PIL import Image
def read_images_from_folder(folder_path):
image_files = []
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".png"):
image_files.append(os.path.join(folder_path, filename))
images = []
for file_path in image_files:
image = Image.open(file_path)
images.append(image)
return images
# 指定文件夹路径
folder_path = "path/to/folder"
# 调用函数读取图片
images = read_images_from_folder(folder_path)
# 对读取到的图片进行操作
for image in images:
# Do something with the image
image.show()
```
在上面的示例中,`read_images_from_folder()` 函数接受文件夹路径作为参数,并返回一个包含所有图片的 `Image` 对象列表。函数首先遍历文件夹中的所有文件,筛选出以 `.jpg` 或 `.png` 结尾的文件路径,并将其存储在 `image_files` 列表中。然后,函数遍历 `image_files` 列表,使用 `Image.open()` 打开每个图片文件,并将其添加到 `images` 列表中。最后,函数返回 `images` 列表。
你可以将 `folder_path` 更改为你想要读取图片的文件夹路径,并使用 `read_images_from_folder()` 函数读取该文件夹中的所有图片文件。然后,你可以对读取到的图片进行进一步的操作,比如显示、处理等。
python读取文件夹中所有图片
可以使用Python的os、glob或者pathlib模块来实现。以下是使用os模块的示例代码:
```python
import os
folder_path = '/path/to/folder' # 文件夹路径
# 遍历文件夹中的所有文件和子文件夹
for root, dirs, files in os.walk(folder_path):
# 遍历当前文件夹中的所有文件
for file in files:
# 如果是图片文件
if file.endswith('.jpg') or file.endswith('.png'):
# 处理该图片文件,例如读取其内容等等
file_path = os.path.join(root, file) # 图片文件路径
# TODO: 处理该图片文件
```
该代码会遍历文件夹中所有的文件和子文件夹,如果该文件是图片文件(以".jpg"或".png"结尾),则处理该文件。你可以在TODO的位置写入处理代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)