Replace string within file contents

后端 未结 8 1773
不知归路
不知归路 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

    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.

提交回复
热议问题