In the below code i am trying to replace the contents of a file which has the following content in it.
hellohello world and the string hellohello should be replaced by hello and be wrote back to the file.Ho to go about this
#!/usr/bin/python
import os
new_file_list=[]
all_files=os.listdir("/tmp")
for ff in all_files:
if ff.endswith(".txt"):
new_file_list.append(ff)
for files in new_file_list:
if files == "a.txt":
print "======================================="
file_name="/tmp/"+str(files)
print file_name
f=open(file_name ,"rw")
while True:
print "======================================="
for line in f.readline():
print line
print "======================================="
f.write(line.replace("hellohello","hello"))
print line
else:
break
for line in f.readline():
print line
f.close()
You can use fileinput module to replace string in a file in place (without opening two files or opening the same file twice or loading entire text file into memory in your code).