2014-04-05 83 views
0

我想一次讀取一行,並將該String分配給我的Python腳本中的變量。一旦這個值被分配,我想從txt文件中刪除該行。剛纔我有下面的代碼:每次腳本運行時從文本文件讀取行並刪除它們

import os 

# Open file with a bunch of keywords 
inputkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') 

# Assigning 
keyword = inputkeywordsfile.readline().strip() 

因此,舉例來說,如果.txt文件具有這樣的結構:

dog 
cat 
horse 

我第一次運行我的腳本,狗將被分配到關鍵字。 第二次運行我的腳本時,貓將被分配給關鍵字,狗將被從文本文件中刪除。

解決:

readkeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') 
firstline = readkeywordsfile.readline().strip() 
lines = readkeywordsfile.readlines() 
readkeywordsfile.close() 

del lines[0:1] 

writekeywordsfile = open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w') 
writekeywordsfile.writelines(lines) 
writekeywordsfile.close() 

keyword = firstline 
+0

[刪除特定線路在一個文件中(蟒)]的可能重複(http://stackoverflow.com/questions/4710067/deleting-a-specific-line-in-a-file- python) – Talvalin

+2

實質上,您需要以讀取模式打開文件,讀取所有行,關閉文件,然後在寫入模式下重新打開文件並寫入要保留的行。 – Talvalin

+1

爲什麼不將文件讀入列表中並根據需要使用列表中的項目? – devnull

回答

0

嘗試了這一點,讓我知道你上車。需要注意的是,在處理文件對象時,Pythonic的方式是使用with open語法,因爲這可以確保文件在離開縮進代碼塊後關閉。 :)

import os 

# Open file with a bunch of keywords 
with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'r') as inputkeywordsfile: 

    # Read all lines into a list and retain the first one 
    keywords = inputkeywordsfile.readlines() 
    keyword = keywords[0].strip() 

with open(os.path.join(os.path.dirname(__file__),'KeywordDatabase.txt'),'w') as outputkeywordsfile: 
    for w in keywords[1:]: 
     outputkeywordsfile.write(w) 
+0

我自己解決了這個問題。您可以查看主消息中的代碼。這樣對嗎? – Alex

+0

這是不正確的。第一次調用readline()會移動文件讀取索引,這樣'lines'只包含剩下的兩個關鍵字。因此,調用'del lines [0:1]'刪除第二個關鍵字,只留下'horse'。刪除'del lines [0:1]'行,它會起作用。 – Talvalin

0

有可能是一個更好的解決辦法或許是。根據我對你的問題的理解,這對我有用。在執行過程中,每條線都分配給變量keyword。這就是我用print keyword來闡述這個事實的原因。此外只是爲了演示我使用time.sleep(5)。在5秒的暫停期間,您可以檢查您的txt文件,它將包含您希望的數據(當第二行分配給變量時,第一行將從txt文件中刪除)。

代碼

import os 
import time 

f = open("KeywordDatabase.txt","r") 
lines = f.readlines() 
f.close() 
k = 0 
for line in lines: 
    if k == 0: 
     keyword = line #Assignment takes place here 
     print keyword 
     f = open("KeywordDatabase.txt","w") 
     for w in lines[k:]: 
      f.write(w) 
     k += 1 
     f.close() 
    else: 
     keyword = line #Assignment takes place here 
     print keyword 
     f = open("KeywordDatabase.txt","w") 
     for w in lines[k:]: 
      f.write(w) 
     f.close() 
     k += 1 
    time.sleep(5) #Time to check the txt file :) 
相關問題