python实现将一个文件夹中所有的非pdf文件删除
时间: 2023-06-12 13:08:00 浏览: 98
好的,您可以按照以下步骤实现:
1. 导入os和shutil模块:
```python
import os
import shutil
```
2. 使用os.listdir()函数获取文件夹中的所有文件,并遍历它们:
```python
folder_path = '/path/to/folder'
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
```
3. 如果文件不是pdf文件,则使用os.remove()函数删除文件:
```python
if not filename.endswith('.pdf'):
os.remove(file_path)
```
4. 最后,您可以使用shutil.rmtree()函数删除空文件夹:
```python
if not os.listdir(folder_path):
shutil.rmtree(folder_path)
```
完整代码如下所示:
```python
import os
import shutil
folder_path = '/path/to/folder'
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if not filename.endswith('.pdf'):
os.remove(file_path)
if not os.listdir(folder_path):
shutil.rmtree(folder_path)
```
希望这可以帮到您!
阅读全文
相关推荐


















