0

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?

3
  • 3
    In what way does it not work? Be specific when asking questions like this Commented Oct 28, 2014 at 21:37
  • never modify a list while iterating over it Commented Oct 28, 2014 at 21:39
  • So I should have to create a new list and then fill it? Commented Oct 28, 2014 at 21:40

5 Answers 5

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

can you explain what splitlines is? I try it in python and it does not recognized it
so maybe I have to import string? Because python says to me AttributeError: 'builtin_function_or_method' object has no attribute 'splitlines'
sorry, my mistake. it should be f.read().splitlines() of course (already edited)
2

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

3 Comments

python gives me an error if I insert this type of text
I use the @Anon code and it works but it removes only from the list and not from the file
OP is using Python 3 (or at least print_function).
0

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)

3 Comments

python gives me an error if I insert this type of text
Is there the possibility to move the code in python model like I wrote it?
because you must remove the >>> , type out line by line without the >>>
0

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.

3 Comments

no it wont ... it will get bad indexes ... it will work in some instances but the indexing will start skipping entries
it technically works because it delete the string but how to delete it also from the file?
this is not how you should be doing it .... it will break on one of the cases that your teacher will probably give you
0

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

2 Comments

if not to_remove in x.lower() is much simpler... also to_remove.lower returns function, so you'll get an error
thats some tricky stuff you are doing with find to ensure it is found at the 0 index ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.