我有线
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
关于python - 使用 fileinput (Python) 进行搜索和替换,同时将消息发送到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668978/