0

我有一个文件,有些行在错误的位置有一个 \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
4

3 回答 3

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)
于 2013-02-19T19:56:46.813 回答
1

这一行:

subp = line.find(".")

不在-1时返回。这弄乱了你的逻辑。"."subp

于 2013-02-19T19:55:33.577 回答
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))

编辑:约翰克莱门茨的答案更好。

于 2013-02-19T19:55:04.963 回答