python读取文件夹中的txt
时间: 2024-12-13 09:06:28 浏览: 7
在Python中,你可以使用os模块以及内置的open()函数或者更高级的pathlib模块来读取文件夹中的所有.txt文件。这里有两个常见的方法:
1. **os.walk() + open()**:
```python
import os
def read_files_in_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.txt'): # 检查是否是.txt文件
with open(os.path.join(root, file), 'r') as f:
content = f.read()
print(f"文件路径: {f.name}, 内容: {content}")
# 使用函数并指定文件夹路径
read_files_in_folder('/path/to/your/folder')
```
2. **pathlib库**:
```python
from pathlib import Path
def read_txt_files_in_folder(folder_path):
folder = Path(folder_path)
txt_files = folder.glob('*.txt')
for txt_file in txt_files:
with open(txt_file, 'r') as f:
content = f.read()
print(f"文件路径: {str(txt_file)}, 内容: {content}")
# 使用函数并指定文件夹路径
read_txt_files_in_folder('/path/to/your/folder')
```
阅读全文