从文件python中的字符串列表中删除特定字符串

时间:2014-10-28 21:35:51

标签: python

我有一个这样的清单:

['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")然后我也要从文件中删除它。我做了类似的事情,但它不起作用。我插入名称,看起来检查名称是否存在但是,当我要求显示文件时,' Lillo,男,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使用此代码。但是如何从文件中删除它?

5 个答案:

答案 0 :(得分: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)] ))

您的整个作业我希望您与班上的其他孩子分享

答案 1 :(得分: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))

答案 2 :(得分: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

答案 3 :(得分:0)

如果要更改文件中的内容,还需要打开要写入的文件。我们也可以使用range(len())来索引值,而不是行。这将有助于弹出

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

这样就可以解决这个问题。

现在您要使用' w'重新打开文件。使用for循环使用新列表覆盖它的权限。

答案 4 :(得分: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年',鲍勃,男,1995年,'菲利克斯,男,1990年,',& #39;贾科莫,男,19 90 \ n',' Irena,女,1992年'乔,男,1995年',' Leo,男,1995年&n' ;,' Marco,男, 1991年\ n',' Tania,女,1992年,' Lillo,男,1994年\ n']