python 读取文件夹内所有图片
时间: 2024-01-24 19:04:21 浏览: 65
要在Python中读取文件夹内所有图片,可以使用os库中的listdir()函数来获取指定文件夹下的所有文件名,然后使用字符串的endswith()方法来筛选出所有以图片格式结尾的文件。以下是一个示例代码:
```
import os
def get_images(folder_path):
images = []
for filename in os.listdir(folder_path):
if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
images.append(os.path.join(folder_path, filename))
return images
if __name__ == '__main__':
folder_path = 'C:/Users/Administrator/Desktop/photo'
images = get_images(folder_path)
print(images)
```
这个代码会返回指定文件夹下所有以.jpg、.png或.jpeg结尾的图片文件的完整路径。你可以根据需要修改文件夹路径和图片格式。
相关问题
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读取文件夹内所有excel
你可以使用Python的`os`和`pandas`库来读取文件夹内所有的Excel文件。下面是一个示例代码:
```python
import os
import pandas as pd
# 设置文件夹路径
folder_path = 'your_folder_path'
# 获取文件夹内所有文件名
file_names = os.listdir(folder_path)
# 遍历文件夹内的文件
for file_name in file_names:
# 判断文件是否为Excel文件
if file_name.endswith('.xlsx') or file_name.endswith('.xls'):
# 构建文件路径
file_path = os.path.join(folder_path, file_name)
# 读取Excel文件
df = pd.read_excel(file_path)
# 处理Excel数据
# 这里可以根据你的需求进行数据处理操作
# 打印数据
print(df)
```
上述代码首先设置了文件夹路径,然后使用`os.listdir()`函数获取文件夹内所有文件的文件名。接下来,通过遍历文件名列表,判断文件是否为Excel文件,如果是,则构建文件路径并使用`pd.read_excel()`函数读取Excel文件。最后,你可以根据你的需求对Excel数据进行处理操作,并打印出来。