python怎么读取一个文件夹里面的所有txt文件
时间: 2023-07-18 08:09:10 浏览: 120
可以使用Python的os和glob模块来读取一个文件夹里面的所有txt文件。具体步骤如下:
1. 导入os和glob模块:
``` python
import os
import glob
```
2. 定义要读取的文件夹路径:
``` python
folder_path = 'your_folder_path'
```
3. 使用glob模块来获取文件夹中所有的txt文件路径:
``` python
txt_files = glob.glob(os.path.join(folder_path, '*.txt'))
```
其中,os.path.join()方法可以将文件夹路径和文件名拼接成完整的文件路径,'*'表示匹配任意字符。
4. 循环读取txt文件内容:
``` python
for txt_file in txt_files:
with open(txt_file, 'r') as f:
content = f.read()
# do something with the content
```
其中,使用with open()语句可以打开txt文件并读取其中的内容。将读取到的内容赋值给变量content,然后可以在循环中对其进行处理。
完整的代码如下:
``` python
import os
import glob
folder_path = 'your_folder_path'
txt_files = glob.glob(os.path.join(folder_path, '*.txt'))
for txt_file in txt_files:
with open(txt_file, 'r') as f:
content = f.read()
# do something with the content
```
注意:在使用os.path.join()方法时,要确保文件夹路径的最后一个字符为'/'或'\\',否则会导致无法正确拼接文件路径。
阅读全文
相关推荐










