python如何获取所有文件并合并
时间: 2023-09-07 18:11:25 浏览: 24
你可以使用Python的os和shutil模块来获取指定目录下的所有文件并进行合并。
首先,通过os模块中的walk函数遍历指定目录下的所有文件:
```python
import os
def get_all_files(path):
file_list = []
for root, dirs, files in os.walk(path):
for file in files:
full_path = os.path.join(root, file)
file_list.append(full_path)
return file_list
```
然后,通过shutil模块中的copy函数将所有文件内容复制到一个新文件中:
```python
import shutil
def merge_files(file_list, output_file):
with open(output_file, 'wb') as f:
for file in file_list:
with open(file, 'rb') as infile:
shutil.copyfileobj(infile, f)
```
最后,调用这两个函数即可实现获取所有文件并合并:
```python
path = '/path/to/dir'
all_files = get_all_files(path)
output_file = '/path/to/output/file'
merge_files(all_files, output_file)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)