读取当前文件夹内的图片python
时间: 2023-09-16 22:08:52 浏览: 39
你可以使用Python中的Pillow库来读取当前文件夹中的图片。以下是一个简单的代码示例:
```python
from PIL import Image
import os
# 获取当前文件夹路径
current_dir = os.getcwd()
# 遍历文件夹中的所有文件
for filename in os.listdir(current_dir):
# 如果是图片文件
if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
# 打开图片文件
image = Image.open(os.path.join(current_dir, filename))
# 处理图片
# ...
```
在此示例中,我们首先使用`os.getcwd()`函数获取当前文件夹路径。然后,我们使用`os.listdir()`函数遍历文件夹中的所有文件,使用`.endswith()`方法判断文件是否为图片文件,如果是,则使用Pillow库中的`Image.open()`函数打开图片文件。需要注意的是,`os.path.join()`函数用于构建文件路径,可以跨平台使用。
相关问题
python读取当前文件夹下所有图片名并输出
你好,可以使用以下代码读取当前文件夹下所有图片名并输出:
```python
import os
# 获取当前文件夹路径
path = os.getcwd()
# 获取当前文件夹下所有文件名
files = os.listdir(path)
# 遍历文件名,输出所有图片名
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
print(file)
```
希望能对你有所帮助。
python读取文件夹内的文件
可以使用Python的os模块和glob模块来读取文件夹内的文件。具体实现代码如下:
```python
import os
import glob
# 获取当前文件夹下所有文件
files = os.listdir('.')
print(files)
# 获取当前文件夹下所有txt文件
txt_files = glob.glob('*.txt')
print(txt_files)
```
其中,os.listdir('.')可以获取当前文件夹下的所有文件,glob.glob('*.txt')可以获取当前文件夹下所有txt文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)