2014-07-24 44 views
1

我有一個製表符分隔的txt文件。最有效地刪除製表符分隔txt的第n行

我想刪除第n個製表符分隔的txt行。

我將指派喜歡

n = 1 

程序將只刪除文件的第一行。

如果程序在沒有讀取整個輸入文件的情況下執行,那麼它會很棒。

我試圖從我以前的一個問題來學習:

Concatenate tab-delimited txt files vertically

這個問題是垂直連接兩個製表符分隔txt文件。所以我認爲扭轉這個過程會爲我做一些類似的事情。但我無法找到如何去做。

我也試過很多其他的計算器答案。

但它們大多 '具有特定短語除去線' 而不是 '除去第n行'

How to delete a line from a text file using the line number in pythonDeleting a specific line in a file (python)Deleting a line from a file in Python

+1

除非線長度都相同,除了讀取要刪除一個所有的線條和打印所有的人。 – tripleee

+1

可能重複[如何使用python中的行號從文本文件中刪除行](http://stackoverflow.com/questions/17747522/how-to-delete-a-line-from-a-text- python) – tripleee

+0

@tripleee雖然這個問題的標題說使用行號刪除,但這個問題實際上並不是。這個問題是明確地分配「短語='狗叫''和刪除與該短語行。 – user3123767

回答

1

您可以使用itertools.islice這一點。這裏循環不Python是涉及所以它應該是快:

from itertools import islice 

n = 4 
with open('file.txt') as f, open('out.txt', 'w') as out: 
    out.writelines(islice(f, n-1)) #write the lines before the nth line 
    out.writelines(islice(f, 1, None)) #write the rest of the lines except nth 
+0

最後一行不應該有'n'而不是'1'嗎? – igor

+1

@igor不,當文件對象已經被分割到第(n-1)行時,它應該是'1'。現在我們需要從第二個索引(1)開始忽略第n行。 –

1
lineToRemove = 7 

f = open("yourfile.txt","r") 
lines = f.readlines() 
f.close() 

f = open("yourfile.txt","w") 
linesInFile = 0 
for line in lines: 
    linesInFile = linesInFile + 1 
    if linesInFile != lineToRemove: 
     f.write(line) 
f.close() 

編輯:通過使用del並省略明確的openclose我們可以減少代碼:

lines = file("yourfile.txt", "r").readlines() 
del lines[6] 
file("yourfile.txt", "w").writelines(lines) 

請注意del lines[6]刪除第7行,因爲索引從零開始。所以,這裏有一個方便的功能,我們可以使用:

def deleteLine(filename, lineToRemove): 
    lines = file(filename, "r").readlines() 
    del lines[lineToRemove-1] 
    file(filename, "w").writelines(lines) 
+0

謝謝!這工作完美。但是,該程序是否讀取整個輸入文件?輸入文件的行具有相同的長度。換句話說,所有行都有相同數量的列。那麼是否有可能不讀取所有行並刪除第n行? – user3123767

+0

這是如何有效的? –