Home > Software engineering >  How do i remove a specific element/text from an file?
How do i remove a specific element/text from an file?

Time:01-14

I dont know what im missing, but i dont seem to be able to remove specific words in an .txt file, ive tried the .remove(), but i received error on that aswell.

if ans == "remove":
    x = input("Clean sheet or some particular?")

    if x == "whole":
        lista.close()
        os.remove("testsamling.txt")
    if x == "some":
        lista = open("testsamling.txt","r")
        print(lista.read())
        ans = input("Which one?")
        
        lista.truncate.index(ans)
        print("has been removed!")

CodePudding user response:

What you could do in the "some" x option is to remove the words from str using replace method and passing an empty string as a second argument to it.

with open("testsamling.txt","r") as f:
   s = f.read()
   updated = s.replace(ans, '')

You can then save the file with:

with open("testsamling.txt","w") as f:
   f.write(updated)

CodePudding user response:

os.remove will delete the file.

What you're looking for is something like,

element_to_remove_from_text_file = 'cat '
file_path = r'C:\my_file.txt'

with open(file_path, mode='r ') as f:
    contents = f.read()
    contents = contents.replace(element_to_remove_from_text_file, '')
    f.seek(0)
    f.write(contents)

CodePudding user response:

use the string.replace() method:

  • open the text : with open(file_path, mode="r") as f
  • make the file readable in python : source_text = f.read()
  • replace the text with an empty string : updated_text = source_text.replace(oldtext, "")
  • write the output to a new file:
    with open(new_file_path, mode="w" as f):
        f.write(updated_text)
    

i went ahead and wrote a small cli for such a task using click (https://click.palletsprojects.com/en/8.0.x/) (only i couldn't be bothered to use an external file and just assigned some random text to the source_text variable :

import click

source_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt \
  esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, \
  sunt in culpa qui officia deserunt mollit anim id est laborum."

@click.command()
@click.option("--to_remove", default=None, prompt="What do you want to delete ?", help="The text you want to remove")
def remove_text(to_remove):
    if str(to_remove) in source_text:
        updated_text = source_text.replace(to_remove, " ")
        click.echo(updated_text)
    else:
        click.echo("Your input is not in the text and could not be deleted")

if __name__ == "__main__":
    remove_text()
  •  Tags:  
  • Related