Click here to Skip to main content
15,905,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have automated finding the people's last names from a text file and I have stored their names in a (var)list I want to delete their last names from the text file.
and I don't fully know how to use truncate
there might be mistakes & if there is not enough information just ask .

What I have tried:

sep = ' '
with open("male.txt", "r+") as f:
    FOUND2die = []
    j = f.readlines()
    f.seek(0)
    for i in j:
        res = i.rsplit(sep, 1)[-1]
        FOUND2die.append(res.strip())
        print(res)
        if i != res:
            f.write(i)
    print("Total Words are "+str(len(FOUND2die)))
    f.truncate()

thank you for your time
Posted
Updated 19-Aug-22 22:08pm

1 solution

The following code does not look correct. The variable i contains the complete line, but res contains only the last word of the line. The chances are that the two will never be the same.
Python
if i != res:
    f.write(i)

Take a look at Built-in Types — Python 3.10.6 documentation[^] for the functions that can be used to remove data from the end of a string.

And you should not write back into your original file, as if anything causes your program to fail mid-processing then all your data may be lost. You should read from the input file, but write the updated information to a new file. That way you can check that the new data is correct before you destroy the original.
 
Share this answer
 
Comments
Hiruy Metsihafe 20-Aug-22 4:20am    
I wanted to read the list then get the last names and find the names in the text file and like delete them
Richard MacCutchan 20-Aug-22 4:41am    
Why do you need the list when you know that the last field of every line is the part to be removed?
Hiruy Metsihafe 20-Aug-22 4:53am    
it was just for testing if its working
Richard MacCutchan 20-Aug-22 5:08am    
Fine but you still need to do what I suggested and use separate input and output files.
Hiruy Metsihafe 20-Aug-22 5:11am    
yes, thanks for the idea. so I have to write it into another file any ideas for writing it in a strip?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900