+ -
当前位置:首页 → 问答吧 → 读文件字符串分割最后一个带了\n,怎么处理?

读文件字符串分割最后一个带了\n,怎么处理?

时间:2011-08-04

来源:互联网


文件为多行
A B C
D E F
1 2 3
字符之间用\t分割

用file.readlines读入
遍历每一样,用split("\t")切

然后得到:
['A', 'B', 'C\n']

囧,因为我要拼东西的,结果最后一个带了\n,换行了

怎么处理呢????

作者: wklken   发布时间: 2011-08-04

我本意想写一个数据格式转换的模块,刚学没几天,哎,求教,谢谢

#!/usr/bin/python
def read_file(path):
  f = open(path,"r")
  lines = f.readlines()
  f.close()
  return lines


def one_line_proc(instr,insp,total,to,outsp):
  parts=instr.split(insp)
  print(parts)
  if len(parts) != len(to):
  print("Error!%s be seplited by %s into %d,not equals to the tuple length")
   
  toindex = 0
  outline=""
  for i in range(1,total+1):
  if toindex!=len(to) and i==to[toindex]:
  outline+=parts[toindex]
  toindex+=1
  else:
  outline+="0"
  if i!=total:
  outline+=outsp
  #print(" "+outline)
  return outline

def process(inpath,insp,total,to,outpath,outsp):
  lines = read_file(inpath)
  f = open(outpath,"w")
  result=[]
  for line in lines:
  print(line),
  outline = one_line_proc(line,insp,total,to,outsp)
  print(outline)
  print("-------")
  result.append(outline)
  f.writelines(result)
  f.close()

inpath="source"
insp="\t"
total=10
to=(1,3,5)

outpath="result"
outsp="-"

process(inpath,insp,total,to,outpath,outsp)

作者: wklken   发布时间: 2011-08-04