我有三个TXT文件在D盘的一个文件夹里,文本内容为很多汉字。怎么用python分别读取它们?写出代码(我后期要对他们进行预处理)
时间: 2024-05-10 15:19:38 浏览: 15
您可以使用Python内置的`open()`函数来读取文本文件,可以使用`for`循环来遍历文件夹中所有的文件。以下是一个读取三个TXT文件的示例代码:
```python
import os
folder_path = 'D:/your/folder/path'
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
file_path = os.path.join(folder_path, file_name)
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
# 进行预处理操作,比如分词等
# ...
```
其中,`folder_path`为文件夹路径,`os.listdir(folder_path)`返回文件夹中所有文件的文件名列表,通过判断文件名是否以`.txt`结尾来确定是文本文件。然后使用`os.path.join(folder_path, file_name)`将文件夹路径和文件名拼接成完整的文件路径,使用`open()`函数打开文件并读取文本内容,最后进行预处理操作。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)