python中,批量读取文件夹中指定子文件夹里的文件,将这个文件复制到指定文件夹里
时间: 2024-03-05 07:52:12 浏览: 155
您可以使用Python的shutil模块来实现将指定文件夹中的特定文件复制到目标文件夹中。具体步骤如下:
1. 导入os和shutil模块
```python
import os
import shutil
```
2. 定义源文件夹路径、目标文件夹路径和需要复制的文件扩展名
```python
source_folder = 'path/to/source/folder'
destination_folder = 'path/to/destination/folder'
file_extension = '.txt'
```
3. 使用os.walk()函数遍历源文件夹中所有子文件夹及其文件
```python
for root, dirs, files in os.walk(source_folder):
for file in files:
if file.endswith(file_extension):
file_path = os.path.join(root, file)
# 处理文件复制
```
4. 使用shutil.copy()函数将满足条件的文件复制到目标文件夹中
```python
for root, dirs, files in os.walk(source_folder):
for file in files:
if file.endswith(file_extension):
file_path = os.path.join(root, file)
shutil.copy(file_path, destination_folder)
```
完整代码示例:
```python
import os
import shutil
source_folder = 'path/to/source/folder'
destination_folder = 'path/to/destination/folder'
file_extension = '.txt'
for root, dirs, files in os.walk(source_folder):
for file in files:
if file.endswith(file_extension):
file_path = os.path.join(root, file)
shutil.copy(file_path, destination_folder)
```
希望这个例子能帮到您!
阅读全文
相关推荐

















