Reputation: 133
I have a list like 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 I want to remove one string just inserted the name (for example "Lillo") then I want to delete it also from a file. I did something like that but it does not work. I insert the name, looks like it check if the name exist but then, when I ask for showing the file, 'Lillo,Male,1994' is still there. Can you help me? Here is my code:
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)
USING THIS CODE FROM @ANON IT WORKS. But how to remove it from the file?
Upvotes: 0
Views: 359
Reputation: 113940
never modify a list while iterating over it
instead filter your list
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)] ))
there is your whole assignment I hope you share with the other kids in your class
Upvotes: 2
Reputation: 6387
You can just process lines you have read into memory and write them to the file (replacing it's content):
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))
Upvotes: 2
Reputation: 19733
the simple one:
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
['Alice,Female,1994\n', 'Bob,Male,1995\n', 'Felix,Male,1990\n', 'Giacomo,Male,19 90\n', 'Irena,Female,1992\n', 'Joe,Male,1995\n', 'Leo,Male,1995\n', 'Marco,Male, 1991\n', 'Tania,Female,1992\n', 'Lillo,Male,1994\n']
Upvotes: 0
Reputation: 11
You will also need to open the file for writing if you want to change what's in the file. We can also use range(len()) to go by index value, rather than the line. That'll help with the popping
for p in range(len(line)):
lineString = line[p].split(',')
if lineString[0] == name:
line.pop(p)
So that'll fix that.
Now you want to re-open the file with 'w' permissions to over-write it with the new list using a for-loop.
Upvotes: 0
Reputation: 122012
In short:
>>> 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']
Firstly, when you read a line, the newline character gets read, so you could do this to remove the newline char:
lines = [l.strip() for l in lines]
Next, since the name always comes in the first column of the comma, you could just use:
lines_with_removed = [l for l in lines if not l.startswith(to_remove)]
Alternatively, you could try csv
(https://docs.python.org/2/library/csv.html)
Upvotes: 0