sprintf like functionality in Python

后端 未结 11 1862
暖寄归人
暖寄归人 2020-12-23 02:50

I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style sprintf functionality in Pyt

11条回答
  •  情话喂你
    2020-12-23 03:09

    Two approaches are to write to a string buffer or to write lines to a list and join them later. I think the StringIO approach is more pythonic, but didn't work before Python 2.6.

    from io import StringIO
    
    with StringIO() as s:
       print("Hello", file=s)
       print("Goodbye", file=s)
       # And later...
       with open('myfile', 'w') as f:
           f.write(s.getvalue())
    

    You can also use these without a ContextMananger (s = StringIO()). Currently, I'm using a context manager class with a print function. This fragment might be useful to be able to insert debugging or odd paging requirements:

    class Report:
        ... usual init/enter/exit
        def print(self, *args, **kwargs):
            with StringIO() as s:
                print(*args, **kwargs, file=s)
                out = s.getvalue()
            ... stuff with out
    
    with Report() as r:
       r.print(f"This is {datetime.date.today()}!", 'Yikes!', end=':')
    

提交回复
热议问题