对dataloader内抛去文件后缀名进行字典序排序的代码
时间: 2023-07-15 17:14:26 浏览: 56
以下是一个简单的 DataLoader 类,用于读取给定目录下的所有文件(不包括子目录),并按字典序排序。在读取文件时,它会跳过不支持的文件类型。
```python
import os
import glob
class DataLoader:
def __init__(self, data_dir):
self.data_dir = data_dir
def load_data(self):
data = []
for file_path in sorted(glob.glob(os.path.join(self.data_dir, '*'))):
if not os.path.isfile(file_path):
continue
file_ext = os.path.splitext(file_path)[-1]
if file_ext not in ['.txt', '.csv']:
continue
with open(file_path, 'r') as f:
content = f.read()
data.append(content)
return data
```
在上面的代码中,我们使用 glob 模块来获取给定目录下的所有文件路径,并使用 os.path 模块来检查每个文件是否是一个有效的文件(不是目录或其他类型的文件)。然后,我们检查文件扩展名是否为支持的类型(这里我们只支持 .txt 和 .csv 文件),并使用 open 函数读取文件内容。最后,我们将文件内容存储在一个列表中,并返回该列表。注意,我们在文件路径上使用 sorted 函数,以确保文件按字典序排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)