2014-10-28 27 views
1

因此,我對Python相當陌生。在經歷了幾個不同的教程之後,我決定嘗試製作一個簡單的程序,其中的一件事是我需要它刪除txt文件中的一行。這是我目前擁有的代碼:從raw_input變量中刪除列表中的數據

name = raw_input("What name would you like to remove: ") 
    templist = open("oplist.txt").readlines() 
    templist_index = templist.index(name) 
    templist.remove(templist_index) 
    target = open("oplist.txt", "w") 
    target.write(templist) 
    target.close 

然而,當templist由它存儲如「例1 \ N」檔,如果用戶只輸入的例子是行不通的數據。有沒有更簡單的方法來解決這個問題?感謝您的幫助。

回答

1

使用rstrip去除新行字符,並使用with來打開文件:

with open("oplist.txt") as f: # with opens and closes the file automtically 
    templist = [x.rstrip() for x in f] # strip new line char from every word 

你也可以Concat的換行字符來命名:

templist_index = templist.index(name+"\n") # "foo" -> "foo\n" 

的完整代碼:

with open("oplist.txt") as f: 
    temp_list = [x.rstrip() for x in f] 
    name = raw_input("What name would you like to remove: ") 
    temp_list.remove(name) # just pass name no need for intermediate variable 
    with open("oplist.txt", "w") as target: # reopen with w to overwrite 
     for line in temp_list: # iterate over updated list 
      target.write("{}\n".format(line)) # we need to add back in the new line 
               # chars we stripped or all words will be on one line 
+0

工程很好,謝謝。現在我只需要了解它的工作原理和原理。 – bebarules666 2014-10-28 23:56:57

+0

我會添加一些評論,但它沒有什麼奇特的想法 – 2014-10-28 23:57:30

+0

是的,我可以很容易地找出發生了什麼事情。就像我之前說的,我仍然是初學者:P – bebarules666 2014-10-28 23:58:29