Python提取并保存txt文件特定列数据

一、提取txt数据特定列数据,并保存的实现步骤:

(1)使用codecs库的open()方法按行读取txt数据。注意txt文件读取时,编码方式设置(例如:encoding='utf-8');

(2)选取txt数据特定列。使用append()方法对特定列数据进行存储;

(3)循环遍历得到的特定列数据,并保存到txt数据文件中;

二、以下案例以保存txt文件的前两列数据为例,使用该方法实现特定列数据保存: 

import codecs

f = codecs.open('1.txt', mode='r', encoding='utf-8')  # 打开txt文件,以‘utf-8'编码读取
line = f.readline()         # 以行的形式进行读取文件
x = []                      # 设置x y z数组
y = []
z = []
while line:
    a = line.split(',')     # 每行数据分隔情况,此数据以“,”分隔
    b = a[0]                # 选取需要读取的数据列数
    c = a[1]
    x.append(b)             # 将其添加在列表之中
    y.append(c)
    x.append(y)
    line = f.readline()
f.close()                   # close文件
f = open (r'new1.txt','w')  # 对获取的txt前两列数据进行保存
for i in x:
    print(i,file = f)
f.close()                   # close文件

你可能感兴趣的:(python)