从fi中删除特定的行返回(“\n”)

2024-10-02 00:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件infotxtifherelineopenelse
3条回答
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)

即使我搞不清楚是怎么回事,这里有一句漂亮的台词:

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更好。你知道吗

这条线:

subp = line.find(".")

"."不在subp时返回-1。这打乱了你的逻辑。你知道吗

相关问题 更多 >

    热门问题