2013-02-19 79 views
0

我有一個文件,有些行在錯誤的位置有\ n。我能夠正確地找到它們,但是當我嘗試將我的發現輸出到一個新文件時,即使打印結果,它們仍會顯示\ 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 
+0

'w.write(line)'應該是'w.write(outputline)'我想。 – utdemir 2013-02-19 19:48:12

+0

沒有一個是正確的,因爲如果該行不需要任何修復。 – rjbogz 2013-02-19 19:49:30

+0

有沒有什麼有趣的與隱藏字符在那裏?像某個地方的「\ r」一樣? – Hoopdady 2013-02-19 19:55:06

回答

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) 
+0

精美完成!我不知道下一個()。謝謝! – rjbogz 2013-02-19 20:01:23

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更好。

+0

雖然這確實使它成爲單線,但它仍然輸出與我相同的結果。 =/ – rjbogz 2013-02-19 19:59:20

1

這條線:

subp = line.find(".") 

回報-1"."subp。這擾亂了你的邏輯。