Python中的txt文件读取方法
注:以txt中带制表符和换行符的文件为例
函数strip(),除去某部分,比如'\n'符号,strip('\n')
函数split(),以某些字符做分割,比如'\t'符号,split('\t')
举例:
python
# 导入路径库,读取图片
import os
train_data_dir = '/train/' # 训练数据集文件夹
with open(train_data_dir+'train_lable.txt','r',encoding='utf-8') as f:
train_data = f.readlines() # 全部读取
print(train_data[0])
train_pic_paths = []
train_pic_labels = []
for words in train_data:
word = words.split('\t') # 制表分割内容,意思不读取制表符
train_pic_paths.append(train_data_dir+word[0])
train_pic_labels.append(word[1].strip('\n')) #去掉换行符
print(train_pic_paths[0])
print(train_pic_labels[0])
print('训练图片数量:',len(train_pic_paths))
输出如下:
train_1_crop_0.jpg 00141
/train/train_1_crop_0.jpg
00141
训练图片数量: 1151