val.txt文件内容有两列,如下:
将第一列数据取出存入新的txt文件,代码如下:
# coding:utf-8
f = open('val.txt') # 打开txt文件
line = f.readline() # 以行的形式进行读取文件
list1 = []
while line:
a = line.split()
b = a[0:1] # 这是选取需要读取的列
list1.append(b) # 将其添加在列表之中
line = f.readline()
f.close()
path_out = 'test.txt' # 新的txt文件
t = ''
with open(path_out, 'w+') as f_out:
for i in list1:
for j in range(len(list1[0])):
t = t + str(i[j])
f_out.write(t)
f_out.write('\n')
t = ''