0

I am writing a script in python that replaces specific lines in files Linux. Say i have a file called hi in the /home directory that contains:

hi 873840

Here is my script:

#! /usr/bin/env python

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)

My desired outcome is:

hi 90

however, when i run it i get this error and the hi file ends up being balnk:

Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer

Is there something wrong with my syntax? Thanks

Irfan
  • 1
  • 1
  • `re.sub(pattern, repl, string, count=0, flags=0)`: third parameter is a string not a file pointer thats why you are getting error. – chakradhar kasturi Nov 16 '17 at 04:24
  • Possible duplicate of [replace string in file with using regular expressions](https://stackoverflow.com/questions/35688126/replace-string-in-file-with-using-regular-expressions) – Clément Denoix Nov 16 '17 at 04:26

2 Answers2

1

use "r" more to read file, "w" mode will create empty file for writing. .readline() will get and pass the string to the re.sub(). r" .*" will return a string you want to replace after the 'space' character. i assume 'hi 873840' is the only text in your file and your desired output is only 'hi 90'

echo "hi 873840" > hi.txt

python3.6

import re
fp = open("hi.txt", "r")
print(re.sub(r" .*", " 90", fp.readline()))
Gio
  • 11
  • 2
0

You should open the file in read mode. re.sub expects three arguments, pattern, repl, string. The problem is the third argument you are passing is a file pointer.
Eg:

import re
with open('/home/hi', 'r', encoding='utf-8') as infile:
    for line in infile:
       print(re.sub(r"hi+", "hi 90", line.strip()))
Arun
  • 1,933
  • 2
  • 28
  • 46