Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanted to remove everything after a specific character if I have a text file with ark yui I want it to delete the yui the character would be a space so what I am trying to say is I want everything to be deleted after a space or any character
if there's anything i am missing please tell me.

What I have tried:

import re
sep = '...'

with open("txtfile.txt") as file_in:
    lines = []
    for line in file_in:
        res = line.split(sep, 1)[0]
        print(res)

but I want it to delete like truncate on that text file
this is my first time so there might be mistakes.
thank you for your time.
Posted
Updated 19-Aug-22 4:38am

1 solution

You can't insert, delete, or truncate a text file - you would have to create a temporary file, copy over all the text up to and including the last characters you want left, then close both files.
Delete the original file, and rename the temporary file to the original name.
 
Share this answer
 
Comments
Hiruy Metsihafe 19-Aug-22 10:43am    
so I have a names txt file and I just want the first names of the people so cant I automate deleting their last names
OriginalGriff 19-Aug-22 11:37am    
No, text files don't work like that - they are just a stream of bytes, some of which are interpreted as "end of line" characters by the processing software.
It's like stack of coins: you can't remove half a dozen coins from the middle because the top would be unsupported.
Hiruy Metsihafe 19-Aug-22 12:10pm    
so what is the code I tried doing
Mike Hankey 19-Aug-22 12:14pm    
If the file is not too large couldn't you read it into memory, modify it and write it back out to the same file?
Hiruy Metsihafe 19-Aug-22 12:17pm    
it's about 1000 words in a strip i wanted to automate it

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