Replace string within file contents

后端 未结 8 1706
不知归路
不知归路 2020-12-01 00:28

How can I open a file, Stud.txt, and then replace any occurences of \"A\" with \"Orange\"?

相关标签:
8条回答
  • 2020-12-01 01:20

    If you are on linux and just want to replace the word dog with catyou can do:

    text.txt:

    Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
    

    Linux Command:

    sed -i 's/dog/cat/g' test.txt
    

    Output:

    Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
    

    Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands

    0 讨论(0)
  • 2020-12-01 01:20

    Using pathlib (https://docs.python.org/3/library/pathlib.html)

    from pathlib import Path
    file = Path('Stud.txt')
    file.write_text(file.read_text().replace('A', 'Orange'))
    

    If input and output files were different you would use two different variables for read_text and write_text.

    If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

    If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.

    0 讨论(0)
提交回复
热议问题