从文件中删除特定行返回(“\ n”)

时间:2013-02-19 19:42:19

标签: python formatting

我有一个文件,有些行在错误的位置有\ n。我能够正确地找到它们,但是当我尝试将我的发现输出到一个新文件时,它们仍会显示\ n即使我打印结果,它们也很好。到目前为止,这是我的代码:

f = open("DUP1.txt","r")
w = open("output.txt", "w")
mark = 0

for line in f:
  if mark == 1:
    mark = 0
    w.write(outputline.replace("\n","\t") + line)
  else:
    subp = line.find(".")
    if subp < 8:
      mark = 1
      outputline = line.replace("\n","")
    else:
      w.write(line)

我打开的文件如下:

ABC0005    other   info    here
ABC0005.23
other      info    here
ABC0005.46
other      info    here

我想让它看起来像:

ABC0005    other   info    here
ABC0005.23 other   info    here
ABC0005.46 other   info    here

3 个答案:

答案 0 :(得分:2)

with open('testdata.txt') as fin, open('testdata.out', 'w') as fout:
    for line in fin:
        if 0 <= line.find('.') <= 8:
            fout.write(line.rstrip() + '\t' + next(fin))
        else:
            fout.write(line)

答案 1 :(得分:1)

这一行:

subp = line.find(".")
-1不在"."时,

会返回subp。这会弄乱你的逻辑。

答案 2 :(得分:0)

即使我无法弄清楚出了什么问题,这里还有一些非常简单的方法:

infile = open("test")
outfile = open("out", "w")    
outfile.writelines(s if not i%2 else s.replace("\n", "\t") for i, s in enumerate(infile))

编辑:John Clements's answer更好。