Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string within file contents

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

like image 735
Joey Avatar asked Nov 08 '10 21:11

Joey


People also ask

How do I replace a word in a text file?

The Ctrl + F and Command + F keyboard shortcut keys also work in Microsoft Excel and other spreadsheet programs to open the Find and Replace text box. In Microsoft Excel, older versions featured the Edit menu, and the Replace option is found in that menu.

How do I replace a string in a list with elements?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .


1 Answers

with open("Stud.txt", "rt") as fin:     with open("out.txt", "wt") as fout:         for line in fin:             fout.write(line.replace('A', 'Orange')) 
like image 95
Gareth Davidson Avatar answered Sep 19 '22 15:09

Gareth Davidson