Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 67012  / 3 Years ago, tue, august 17, 2021, 11:39:21

Through python script, I am trying to replace a string by a string in a file using sed command. I do that through subprocess.call as it in the script.



When I run the command in the shell script or command, it runs fine, but in python I get a result saying "No input file".
Any idea how to fix that error?



#!/usr/bin/python
import subprocess
subprocess.call(["sed -i -e 's/hello/helloworld/g'","www.txt"], shell=True)


Output



No input file

More From » scripts

 Answers
1

You should avoid subprocess and implement the functionality of sed with Python instead, e.g. with the fileinput module:



#! /usr/bin/python
import fileinput
for line in fileinput.input("www.txt", inplace=True):
# inside this loop the STDOUT will be redirected to the file
# the comma after each print statement is needed to avoid double line breaks
print line.replace("hello", "helloworld"),

[#16184] Wednesday, August 18, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jectedrin

Total Points: 491
Total Questions: 105
Total Answers: 111

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;