Friday, 15 January 2010

Delete a specific string from a list of strings in a file python -



Delete a specific string from a list of strings in a file python -

i have list that:

['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']

then want remove 1 string inserted name (for illustration "lillo") want delete file. did not work. insert name, looks check if name exist then, when inquire showing file, 'lillo,male,1994' still there. can help me? here code:

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

using code @anon works. how remove file?

you can process lines have read memory , write them file (replacing it's content):

name = input("insert name want delete: ") # let's strip excessive whitespace , alter lower case: name = name.strip().lower() book = "data.txt" # utilize 'with' build ensure file closed after use: open(book, 'r') f: lines = f.read().splitlines() filtered = [] line in lines: try: # guard against wrong record, e.g. 'guido, 1956' name_, sex, year = line.split(',') except valueerror: print("cannot unpack line:", line) go on if name == name_.strip().lower(): go on # don't want line, skip filtered.append(line) # line ok, maintain # bring together list of lines 1 string , write file: open(book, 'w') f: f.write('\n'.join(filtered))

python

No comments:

Post a Comment