2016-12-01 219 views
2

我遇到的另一個問題是,我有此代碼從文本文件中刪除名稱。我不完全確定爲什麼,但有時它可以正常工作,並刪除了名稱,但通常情況並非如此,是否有更好的方法可以在100%的時間內正常工作?我已經改變了我的文件路徑和文件名,因爲你們不需要它。從文本文件中刪除名稱

with open(r"MyFilePath\MyFile.txt","r") as file: 
     participants=[] 
     for line in file: 
      participants.append(line) 
    file.close() 
    leavingParticipant=input("Enter leaving participant: ") 
    file=open(r"MyFilePath\MyFile.txt","w") 
    for participant in participants: 
     if participant!=leavingParticipant+"\n": 
      file.write(participant) 
    file.close() 
+0

從只盯着你的代碼我最好的猜測是,它與'leavingParticipant +「\ n」來辦'...你可以粘貼一些樣本數據? – anshanno

回答

2
with open(r"MyFilePath\MyFile.txt","r") as file: 
    participants=[] 
    for line in file: 
     participants.append(line) 

leavingParticipant=input("Enter leaving participant: ") 

with open(r"MyFilePath\MyFile.txt","w") as file: 
    for participant in participants: 
     if leavingParticipant != participant.strip(): 
      file.write(participant) 

您不需要在上下文管理器(該with..as語句)手動關閉文件。與其試圖圍繞我們需要的信息播放空白,我們只是將其刪除以供比較。

+0

謝謝,沒有改變我做過的很多東西 – WhatsThePoint

2

首先,你並不需要閱讀的線條和它們添加到列表中手動因爲每當你打開文件open()函數返回一個文件對象,它是一個包含所有行的迭代器狀物體。或者如果你想緩存它們,你可以使用readlines()方法。

其次,當您使用with語句時,不需要關閉文件,這正是關閉塊末尾文件的其中一個作業。

考慮到上述提示,您可以選擇使用臨時文件對象一次讀取和修改文件的最佳方法。幸運的是,python爲我們提供了tempfile模塊,您可以在這種情況下使用NamedTemporaryFile方法。並使用shutil.move()將臨時文件替換爲當前文件。

import tempfile 
import shutil 

leavingParticipant=input("Enter leaving participant: ") 
filename = 'filename' 
with open(filename, 'rb') as inp, tempfile.NamedTemporaryFile(mode='wb', delete=False) as out: 
    for line if inp: 
     if line != leavingParticipant: 
      put.write(line) 


shutil.move(out.name, filename) 
0

讓我們重新編寫一些代碼。首先file是一個保留字,所以最好不要超載它。其次,由於您使用with來打開文件,因此不需要使用.close()。它在with子句結束時自動執行。您不需要遍歷參與者列表。有幾種方法可以處理從列表中刪除項目。使用.remove(item)可能是最合適的。

with open(r"MyFilePath\MyFile.txt","r") as fp: 
    participants=[] 
    for line in fp: 
     participants.append(line.strip()) #remove the newline character 

leavingParticipant = input("Enter leaving participant: ") 

with open(r"MyFilePath\MyFile.txt","w") as fp2: 
    if leavingParticipant in participants: 
     participant.remove(leavingParticipant) 
    file.write('\n'.join(participant)) 
+1

@Patrick:這是不正確的。使用'in'在字符串列表中搜索完全匹配。它不會將搜索映射到列表中的每個字符串中。 – James