遍历读取文件夹各个文件的数据

需求:

希望得到一个列表,该列表保存了train文件夹内所有文件的信息。(如下图所示)

image.png

import os
train_dir = "./train"
text = [] # 用来存储各个文件中的数据
for fname in os.listdir(train_dir): # 遍历读取train_dir中的文件名
    if fname[-4:] == ".text": # 判断文件类型是否属于.tet文件
        f = open(os.path.join(train, fname) # 使用open函数打开文件
        text.append(f.read()) # 将文件内容保存进text列表中
        f.close

新增需求:

train下同时有neg、pos两种标签的数据,我希望使用一段代码同时读取这两个文件夹中的文件内容

image.png

import os
Imdb_dir = "./aclimdb"
trian_dir = os.path.join(Imdb_dir, "trian")
text = [] # 用来存储各个文件中的数据
labels = [] # 用来数据的类别
for label_type in ["neg", "pos"]: # 通过这种方式,依次遍历neg文件夹和pos文件夹
    dir_name = os.path.join(train_dir, "label_type") # 生成包含neg或pos的新路径
    for fname in os.listdir(dir_name): # 遍历neg或pos文件夹中的所有文件
        if fname[-4:] == ".text": # 判断文件类型是否属于.tet文件
        f = open(os.path.join(train, fname) # 使用open函数打开文件
        text.append(f.read()) # 将文件内容保存进text列表中
        f.close
        if label_type == "neg": # 判断文件是否位于neg文件夹下
            labels.append(0) # 给相关数据加上标签
        else:
            labels.append(1)

完!

posted @ 2024-04-15 10:16  wuhaoliu  阅读(17)  评论(0)    收藏  举报  来源