How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:
I am using the with statement in this example, which closes the file after the
with
block is terminated - either normally when the last command finishes executing, or by an exception.It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single
with
statement.If you are on linux and just want to replace the word
dog
withcat
you can do:text.txt:
Linux Command:
Output:
Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
Something like
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...