2014-01-30 246 views
8

我正在編寫修改任何文本文件的腳本。它用空行代替空白行。它會擦除文件末尾的空白行。該圖像顯示我想要的輸出。Python - 刪除文件末尾的空行文本

enter image description here

我能夠得到非常接近所需的輸出。問題是我無法擺脫最後一個空白行。我認爲這與最後一行有關。例如' the lines below me should be gone實際上看起來像這樣' the lines below me should be gone\n'它看起來像在上一行創建了新行。 e.g如果4號線有\n比5號線實際上將是空行不行4.

我要指出,我不能使用rstripstrip

到目前爲止我的代碼。

def clean_file(filename): 
    # function to check if the line can be deleted 
    def is_all_whitespace(line): 
     for char in line: 
      if char != ' ' and char != '\n': 
       return False 
     return True 

    # generates the new lines 
    with open(filename, 'r') as file: 
     file_out = [] 
     for line in file: 
      if is_all_whitespace(line): 
       line = '\n' 
      file_out.append(line) 

    # removes whitespaces at the end of file 
    while file_out[-1] == '\n': # while the last item in lst is blank 
     file_out.pop(-1) # removes last element 

    # writes the new the output to file 
    with open(filename, 'w') as file: 
     file.write(''.join(file_out)) 

clean_file('test.txt') 
+3

你已經做了很多關於這個問題的研究,這很清楚。 +1。 – jayelm

+1

爲什麼「不能」使用'.rstrip()'? –

+0

@KarlKnechtel那會太容易 – Vader

回答

6

\n基本上意味着,當你刪除了所有的都是\n線「創建另一個行」

所以,還是有前行

the lines below me should be gone\n 

這又意味着「創建另一行「,超出已刪除的行號

既然你說你不能使用rstrip,那麼你可以結束循環與

file_out[-1] = file_out[-1].strip('\n') 

刪除\n從最後一個元素。因爲\n不能在一條線上其他任何地方,rstripstrip將有同樣的效果

或者沒有任何stripendswith

if file_out[-1][-1] == '\n': 
    file_out[-1] = file_out[-1][:-1] 

注意\n是單個字符,依次0x0a作爲十六進制,不是兩個字符\n,序號0x5c0x6e。這就是爲什麼我們使用-1而不是-2

+0

@Vader然後我懷疑你可以使用'file_out [-1] [ - 1] =='\ n''。 – Santa

+0

@Vader你爲什麼想用'-2'? ''\ n''是一個字符。 – Santa

+0

@Vader''\ n''是一個**字符,表示「換行符」。反斜槓(''\')'是一種轉義,以區別於常規的''n''。 – Santa