0

I have a text file (file1.txt) containing pattern like this.

****
****
****
****

I want to replace it by **. I can use command something like this sed -i 's/\*{4}/**/' file1.txt in linux to get in place replacement. But I want to do this operation in Windows environment using python script.

import re
with open ('file1.txt') as fil1:
     for line in fil1:
         re.sub('^\*{3}[*]*','**',line)

But this script does not seem to replace **** by ** in place in the file. How can I get in place file replacement (similar to sed command) in python?

Edit:

I do not want to read file line by line, replace text and write the line into another file. I want to do something like sed -i to do in place file replacement in python using regular expressions.

cs95
  • 379,657
  • 97
  • 704
  • 746
dfs3w
  • 3
  • 2
  • 1
    In what way does it not work? – klutt Jul 23 '17 at 18:28
  • Updated question – dfs3w Jul 23 '17 at 18:30
  • 1
    The problem is that you're not writing anything. You are just reading from the file to the variable line and change the variable. – klutt Jul 23 '17 at 18:31
  • Possible duplicate of [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – klutt Jul 23 '17 at 18:33
  • You _cannot_ get any kind of 'in-place' changes in a file. You only can read from it and write into it. And all of this has to be done explicitly. – ForceBru Jul 23 '17 at 18:33
  • Doesn't `re.sub` replace and write in the file like `sed` ? – dfs3w Jul 23 '17 at 18:33
  • @dfs3w, no, it doesn't. Also, given that you ignore its return value, in your code it doesn't do anything at all. – ForceBru Jul 23 '17 at 18:35
  • OK. How can I do in place replacement in python using regular expressions? – dfs3w Jul 23 '17 at 18:50

1 Answers1

0

You're trying to edit the file inlace, but you open the file in read mode, so it is not open for writing.

Furthermore, you are calling re.sub which returns a new string that you do not capture and attempt to write.

Editing a file inplace is challenging with the builtin functions, but is made easy with the fileinput module:

import fileinput

with fileinput.FileInput('file1.txt', inplace=True) as fil1:
    for line in fil1:
        text = re.sub('^\*{3}[*]*','**', line.rstrip()).strip()
        if text:
            print(text) # inside the `with` clause, print writes to the file automatically 
cs95
  • 379,657
  • 97
  • 704
  • 746
  • It inserts blank like in the last line of the file. Do you know how to get rid of that? – dfs3w Jul 23 '17 at 19:07
  • @dfs3w Your input file probably has that. Check my edit? And if it helps, do mark it accepted :) – cs95 Jul 23 '17 at 19:09