2015-06-30 114 views
-4

我正在尋找代碼解決方案。我需要使用python刪除一段文件,這裏有5行代碼。從文本文件(Python)中刪除大塊文本

Numberplate: BN30CWS 

Time In: Time In: 11:11:3 

Time Out: Time In: 11:11:51 

Speed: Your Speed: 48MPH 

Was this vechile speeding?: No 

(無縫隙)

所以,如果我進入BN30CWS我想那些5行從文件(fileDocStandard)請幫忙刪除,我試圖做4小時,該工作代碼現在,這就是我今天來了,但它只是刪除1行,不會刪除孔塊

def deldata(): 
file = open(fileDocStandard, "r") 
array = [] 
for line in file: 
    array.append(line) 
file.close() 

for i in range(len(array)): 
    print (array[i]) 
let = input("Please enter the plate you want to delete ") 
let = let.upper() 
for i in range(len(array)): 
    arrayitem = array[i] 

    if (arrayitem[0]) == (let): 
     del (array[i]) 
     break 
file = open(fileDocStandard, "w") 
file.close() 
file = open(fileDocStandard, "a") 
for i in range(len(array)): 
    file.write(array[i]) 
file.close() 

任何人看到這個問題,並能幫助我終於完成這個?

+1

我投票關閉此作爲題外話題,因爲這不是一個代碼寫作或教程服務 – jonrsharpe

+0

請詳細提及你的問題,我無法說出它的話! – CrakC

+0

我試過了,是的,我已經嘗試使用數組來讀取文件,但我無法弄清楚如何刪除它或選擇不僅僅是1行 –

回答

0

您可以閱讀您的線條,直到您到達BN30CWS所在的線條。然後使用itertools.islice通過未來5行,寫你的線條一個新的文件中:

from itertools import islice 

with open(fileDocStandard) as f,open(newfile) as out: 
    for line in f: 
     if 'BN30CWS' in f: 
      f=islice(f,5,None) 
     out.write(line) 

如果你想覆蓋該文件可以使用tempfile

with tempfile.NamedTemporaryFile(delete=False) as outfile: 
    with open(fileDocStandard) as f: 
     for line in outfile: 
      if 'BN30CWS' in line: 
       outfile=islice(outfile,5,None) 
      out.write(line) 
    os.rename(outfile.name, fileDocStandard) 
+0

謝謝你的答覆這個作品:)只需要編輯它的代碼,它syhould工作謝謝 –

+0

@MikeMarsh不客氣! – Kasramvd