I have lines
for line in fileinput.input(file_full_path, inplace=True):
newline, count = re.subn(search_str, replace_str, line.rstrip())
# ... display some messages to console ...
print newline # this is sent to the file_full_path
which are supposed to replace all occurrences of search_str
in the file file_full_path
and replace them with replace_str
. The fileinput
maps stdout
to the given file. So, print newline
and things sent to sys.stdout
are sent to the file and not to the console.
I would like to, in the middle of the process, display some messages to console, e.g. I could show the portion of the line in which the replacement is going to occur, or some other messages, and then continue with the print newline
into the file. How to do this?
From Python docs:
Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).
so you should write to stderr to display messages in the console, like this:
import sys
for line in fileinput.input(file_full_path, inplace=True):
newline, count = re.subn(search_str, replace_str, line.rstrip())
sys.stderr.write("your message here")
print newline
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With