使用python从.txt文件中删除匹配的行

时间:2011-07-10 05:00:56

标签: python file text-files

我正在创建一个删除功能。

my customerlist.txt

[1. 'Yuvin Ng', 'Columbia College', 778]
[2, 'Ali', 'Douiglas College', 77238]
[3, 'Nancy', 'Douglas College', 7783390222]

如果我想删除Yuvin Ng及其整行,我该怎么办?

我的计划是创建一个空列表,将整个内容返回为“”并将其保存回.txt文件。

我的代码

def deletecustomer(file_name,name):
    f=open(file_name,"r+")
    c=""
    for line in f:
        if name in line:
      - - - -- - --  -  -- #how can i make it read every line at position list[0] from list
     - ------ -- - -- - - -#take the selected list of the and erase by replacing the whole list with " "

我无法想出办法来解决这个问题。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望返回文件内容减去删除的行

ret = []
for line in f:
    if name != line[1]:
        ret.append(line);
return ret

答案 1 :(得分:1)

new_file = open(nf,'w')
with open(fn) as f:
    for l in f:
        if not 'Yuvin Ng' in l:
            new_file.write(l)
相关问题