在python中,如何实现多个文档的读取功能
时间: 2024-03-05 13:54:41 浏览: 28
在Python中,可以使用多种方式来实现多个文档的读取功能,下面是其中几种方式的示例代码:
1. 使用for循环逐个读取文档
```python
# 定义文档路径
doc_paths = ["doc1.txt", "doc2.txt", "doc3.txt"]
# 逐个读取文档
for path in doc_paths:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
# 处理文档内容
# ...
```
2. 使用glob模块获取文档路径列表
```python
import glob
# 定义文档路径的通配符
doc_pattern = "*.txt"
# 获取所有符合通配符的文档路径
doc_paths = glob.glob(doc_pattern)
# 逐个读取文档
for path in doc_paths:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
# 处理文档内容
# ...
```
3. 使用os模块遍历目录获取文档路径列表
```python
import os
# 定义文档所在的目录路径
doc_dir = "/path/to/docs"
# 遍历目录获取所有文档的路径列表
doc_paths = []
for root, dirs, files in os.walk(doc_dir):
for file in files:
if file.endswith(".txt"):
path = os.path.join(root, file)
doc_paths.append(path)
# 逐个读取文档
for path in doc_paths:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
# 处理文档内容
# ...
```
以上示例代码中,需要根据实际情况修改文档路径、通配符或目录路径等参数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)