2014-12-06 152 views
-1

我在刪除文本文件中的特定行/條目時遇到問題。無論我選擇刪除哪一行號碼,使用代碼我都會刪除該文件中的第一行。刪除Python中的txt文件中的一行

def erase(): 
    contents = {} 
    f = open('members.txt', 'a') 
    f.close() 
    f = open('members.txt', 'r') 
    index = 0 
    for line in f: 
     index = index + 1 
     contents[index] = line 
     print ("{0:3d}) {1}".format(index,line)) 
    f.close() 
    total = index 
    entry = input("Enter number to be deleted") 
    f = open('members.txt', 'w') 
    index = 0 
    for index in range(1,total): 
     index = index + 1 
     if index != entry: 
     f.write(contents[index]) 
+1

從'範圍'中的'index == 1'開始,在*寫之前增加*; Python索引是基於'0'的,所以你跳過前兩行('0'和'1')。 – jonrsharpe 2014-12-06 16:32:29

回答

-1

試試這個:

import sys 
import os 

def erase(file): 
    assert os.path.isfile(file) 
    with open(file, 'r') as f: 
     content = f.read().split("\n") 
    #print content                                                                
    entry = input("Enter number to be deleted:") 
    assert entry >= 0 and entry < len(content) 
    new_file = content[:entry] + content[entry+1:] 
    #print new_file                                                                
    with open(file,'w') as f: 
     f.write("\n".join(new_file)) 

if __name__ == '__main__': 
    erase(sys.argv[1]) 

如前所述你是從1這是不正確啓動範圍。我在new_file = content[:entry] + content[entry+1:]中使用的列表切片使得代碼更具可讀性,並且這種方法不太容易出現類似的錯誤。

此外,你似乎無緣無故打開和關閉輸入文件的開始。如果可能的話,你也應該使用with

最後,我使用了joinsplit來簡化代碼,因此您不需要for循環來處理文件的行。