用了两种方式解决该问题,都是网上现有的解决方案。
场景说明:
有一个数据文件,以文本方式保存,现在有三列user_id,plan_id,mobile_id。目标是得到新文件只有mobile_id,plan_id。
解决方案
方案一:用python的打开文件写文件的方式直接撸一遍数据,for循环内处理数据并写入到新文件。
代码如下:
def readwrite1( input_file,output_file):
f = open(input_file, "r")
out = open(output_file,"w")
print (f)
for line in f.readlines():
a = line.split(",")
x=a[0] + "," + a[1]+" "
out.writelines(x)
f.close()
out.close()
方案二:用 pandas 读数据到 DataFrame 再做数据分割,直接用 DataFrame 的写入功能写到新文件
代码如下:
def readwrite2(input_file,output_file): date_1=pd.read_csv(input_file,header=0,sep=",") date_1[["mobile", "plan_id"]].to_csv(output_file, sep=",", header=True,index=False)
从代码上看,pandas逻辑更清晰。