0

I want to open a txt file and replace all "hello" to "love" and save it and do not create a new file. Just modify the content in the same txt file.

My code just can add "love" after "hello", rather than substitute them.

Any method can fix it?

Thx so much

f = open("1.txt",'r+')
con = f.read()
f.write(re.sub(r'hello','Love',con))
f.close()
Luke
  • 11
  • 3
  • 1
    http://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python – Blorgbeard Jul 13 '15 at 04:09
  • 1
    Maybe this has the answer for your question [How to search and replace text in a file using Python?](http://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python) – GAVD Jul 13 '15 at 04:10

2 Answers2

0

After you read the file, the file pointer is at the end of the file; if you write then, you will append to the end of the file. You want something like

f = open("1.txt", "r")  # open; file pointer at start
con = f.read()          # read; file pointer at end
f.seek(0)               # rewind; file pointer at start
f.write(...)            # write; file pointer somewhere else
f.truncate()            # cut file off in case we didn't overwrite enough
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

You can create a new file and replace all words you find in the first, write them in the second. See How to search and replace text in a file using Python?

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()

Or, you can use fileinput

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    line = line.replace("hello","love")
Community
  • 1
  • 1
GAVD
  • 1,977
  • 3
  • 22
  • 40
  • All this holds until you have to replace a smaller word with the longer one. In this case, you will have to do it in memory or use mmap module to change the file's size at runtime, move characters on their new positions and insert what you need. For other cases seek() tell() and truncate() will help. – Dalen Jul 13 '15 at 04:43
  • Aha, yeah, to be clear, you can move your file content into the right position without mmap, but this will kill you and OS more efficiently. mmap allows you to use RAM or disk memory as a mutable string. – Dalen Jul 13 '15 at 04:46