
Replace string within file contents
By: a guest on
Feb 22nd, 2012 | syntax:
None | size: 1.25 KB | hits: 10 | expires: Never
with open("out.txt", "wt") as out:
for line in open("Stud.txt"):
out.write(line.replace('A', 'Orange'))
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
text_file = open("file.txt", "rw")
whole_thing = text_file.read()
whole_thing = whole_thing.replace("A", "Orange");
text_file.write(whole_thing);
text_file.close();
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
import re
input = file('C:full_pathStud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:full_pathStud.txt), 'w')
for each in saved_input:
input.write(each)