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

2

2 Answers 2

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()))
Sign up to request clarification or add additional context in comments.

2 Comments

Text that describe the solution you've come up with would be useful to the person who asked the question.
thank for the reminder and suggestion. new to stackoverflow
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()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.