2014-10-28 18 views
0

我有一個這樣的名單:文件中的巨蟒從一個字符串列表中刪除特定字符串

['Alice,Female,1994\n', 'Bob,Male,1995\n', 'Carol,Male,1993\n', 'Felix,Male,1990\n',  'Giacomo,Male,1990\n', 'Irena,Female,1992\n', 'Joe,Male,1995\n', 'Leo,Male,1995\n', 'Marco,Male,1991\n', 'Tania,Female,1992\n', 'Lillo,Male,1994'] 

然後我想刪除一個字符串剛插入的名稱(例如「利洛」),那麼我想要從文件中刪除它。我做了這樣的事情,但它不起作用。我插入名稱,看起來像檢查名稱是否存在,但當我要求顯示文件時,'Lillo,Male,1994'仍然存在。你可以幫我嗎?這裏是我的代碼:

name = input("Insert the name you want to delete: ") 
book = "data.txt" 
f = open(book,'r') 
line = f.readlines() 
f.close() 
print(line) 
for p in range(len(line)): 
    lineString = line[p].split(',') 
    if lineString[0] == name: 
     line.pop(p) 
print(line) 

使用此代碼@ANON IT WORKS。但如何從文件中刪除它?

+3

它不工作的方式?當提問這樣的問題時,請具體說明 – 2014-10-28 21:37:06

+0

__never__在迭代時修改列表 – 2014-10-28 21:39:49

+0

所以我應該創建一個新列表然後填寫它? – pp94 2014-10-28 21:40:30

回答

2

你可以只生產線已讀入內存中,並寫入到文件(替換其內容):

name = input("Insert the name you want to delete: ") 
# let's strip excessive whitespace and change to lower case: 
name = name.strip().lower() 
book = "data.txt" 

# use 'with' construct to ensure that file is closed after use: 
with open(book, 'r') as f: 
    lines = f.read().splitlines() 

filtered = [] 
for line in lines: 
    try: # guard against incorrect record, e.g. 'Guido, 1956' 
     name_, sex, year = line.split(',') 
    except ValueError: 
     print("cannot unpack this line:", line) 
     continue 
    if name == name_.strip().lower(): 
     continue # we don't want this line, so we skip it 
    filtered.append(line) # line is ok, we keep it 

# join list of lines into one string and write to the file: 
with open(book, 'w') as f: 
    f.write('\n'.join(filtered)) 
+0

你能解釋什麼是分裂線嗎?我嘗試在Python中,它不承認它 – pp94 2014-10-28 22:13:05

+0

這一切都在文檔︰https://docs.python.org/2/library/stdtypes.html#str.splitlines – 2014-10-28 22:14:48

+0

所以也許我必須導入字符串?因爲python對我說AttributeError:'builtin_function_or_method'對象沒有屬性'splitlines' – pp94 2014-10-28 22:16:05

0

簡而言之:

>>> lines = ['Alice,Female,1994\n', 'Bob,Male,1995\n', 'Carol,Male,1993\n', 'Felix,Male,1990\n',  'Giacomo,Male,1990\n', 'Irena,Female,1992\n', 'Joe,Male,1995\n', 'Leo,Male,1995\n', 'Marco,Male,1991\n', 'Tania,Female,1992\n', 'Lillo,Male,1994'] 
>>> lines = [l.strip() for l in lines] 
>>> to_remove = 'Giacomo' 
>>> lines_with_removed = [l for l in lines if not l.startswith(to_remove)] 
>>> lines_with_removed 
['Alice,Female,1994', 'Bob,Male,1995', 'Carol,Male,1993', 'Felix,Male,1990', 'Irena,Female,1992', 'Joe,Male,1995', 'Leo,Male,1995', 'Marco,Male,1991', 'Tania,Female,1992', 'Lillo,Male,1994'] 

首先,當你讀一行,換行符被讀取,所以你可以做到這一點,除去換行字符:

lines = [l.strip() for l in lines] 

其次,由於名稱總是出現在逗號的第一列,您可以使用:

lines_with_removed = [l for l in lines if not l.startswith(to_remove)] 

或者,您可以嘗試使用csvhttps://docs.python.org/2/library/csv.html)在遍歷它

,而不是過濾列表,

+0

如果我插入這種類型的文本,python會給我一個錯誤 – pp94 2014-10-28 21:46:30

+0

是否有可能像我寫的那樣在python模型中移動代碼? – pp94 2014-10-28 21:48:18

+0

,因爲你必須刪除'>>>',一行一行地輸入而不用'>>>' – alvas 2014-10-29 08:41:12

2

從未修改列表

def test(line): 
    this_name = line.split(",",1)[0] 
    return name == this_name 

name = input("Insert the name you want to delete: ") 
book = "data.txt" 
lines = open(book,'r').readlines() 
with open(book,"wb") as f: 
    f.write("\n".join([line for line in lines if test(line)])) 

有你的整個任務,我希望你在你的班上其他孩子分享

+0

python給我一個錯誤,如果我插入這種類型的文本 – pp94 2014-10-28 21:45:46

+0

我使用@Anon代碼,它可以工作,但它刪除只有從列表而不是從文件 – pp94 2014-10-28 21:57:57

+1

OP正在使用Python 3(或至少是'print_function')。 – 2014-10-28 22:25:07

0

如果您想更改文件內容,您還需要打開文件進行寫入。我們也可以使用range(len())按索引值而不是行。這將有助於彈出

for p in range(len(line)): 
    lineString = line[p].split(',') 
    if lineString[0] == name: 
     line.pop(p) 

因此,這將解決這一問題。

現在您想要使用'w'權限重新打開該文件,並使用for-loop將其重寫爲新列表。

+0

不,它會得到不好的索引...它會在某些情況下工作,但索引將開始跳過條目 – 2014-10-28 21:51:19

+0

它在技術上的工作原理是因爲它刪除字符串,但如何刪除它也從文件? – pp94 2014-10-28 21:54:53

+0

這不是你應該怎麼做的......它會打破你的老師可能會給你的一個案例 – 2014-10-28 21:58:44

0

簡單的一個:

line=['Alice,Female,1994\n', 'Bob,Male,1995\n', 'Carol,Male,1993\n', 'Felix,Male,1990\n',  'Giacomo,Male,1990\n', 'Irena,Female,1992\n', 'Joe,Male,1995\n', 'Leo,Male,1995\n', 'Marco,Male,1991\n', 'Tania,Female,1992\n', 'Lillo,Male,1994'] 
to_remove = 'carol' 
new_line = [ x for x in line if not x.strip().lower().find(to_remove.lower()) ] 
new_line 

['愛麗絲,女, 1994 \ n','Bob,Male,1995 \ n','Felix,Male,1990 \ n','Giacomo,Male,19 90 \ n','Irena,Female,1992 \ n','Joe,男,1995 \ n','Leo,Male,1995 \ n','Marco,男, 1991 \ n','Tania,女,1992 \ n','Lillo,男,1994 \ n']

+0

'如果不能在x.lower()中移除''要簡單得多...也''to_remove.lower'返回函數,所以你會得到一個錯誤 – 2014-10-28 22:21:07

+0

ohh輸入錯誤 – Hackaholic 2014-10-28 22:23:34

+0

多數民衆贊成在一些棘手的東西,你正在做的事情發現,以確保它在0索引處找到... – 2014-10-28 22:40:02

相關問題