使用文件输入 (Python) 进行搜索和替换,同时向控制台发送消息
Using fileinput (Python) for a search-and-replace while also sending messages to console
我有台词
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
应该替换文件 file_full_path
中出现的所有 search_str
,并将它们替换为 replace_str
。 fileinput
将 stdout
映射到给定的文件。因此,print newline
和发送到 sys.stdout
的东西被发送到文件而不是控制台。
我想在此过程中向控制台显示一些消息,例如我可以显示行中将要进行替换的部分,或一些其他消息,然后继续 print newline
到文件中。如何做到这一点?
来自 Python 文档:
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).
所以你应该写入 stderr 以在控制台中显示消息,如下所示:
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
我有台词
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
应该替换文件 file_full_path
中出现的所有 search_str
,并将它们替换为 replace_str
。 fileinput
将 stdout
映射到给定的文件。因此,print newline
和发送到 sys.stdout
的东西被发送到文件而不是控制台。
我想在此过程中向控制台显示一些消息,例如我可以显示行中将要进行替换的部分,或一些其他消息,然后继续 print newline
到文件中。如何做到这一点?
来自 Python 文档:
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).
所以你应该写入 stderr 以在控制台中显示消息,如下所示:
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