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
If I understand your question correctly, format() is what you are looking for, along with its mini-language.
Silly example for python 2.7 and up:
>>> print "{} ...\r\n {}!".format("Hello", "world")
Hello ...
world!
For earlier python versions: (tested with 2.6.2)
>>> print "{0} ...\r\n {1}!".format("Hello", "world")
Hello ...
world!
This is probably the closest translation from your C code to Python code.
A = 1
B = "hello"
buf = "A = %d\n , B= %s\n" % (A, B)
c = 2
buf += "C=%d\n" % c
f = open('output.txt', 'w')
print >> f, c
f.close()
The %
operator in Python does almost exactly the same thing as C's sprintf
. You can also print the string to a file directly. If there are lots of these string formatted stringlets involved, it might be wise to use a StringIO
object to speed up processing time.
So instead of doing +=
, do this:
import cStringIO
buf = cStringIO.StringIO()
...
print >> buf, "A = %d\n , B= %s\n" % (A, B)
...
print >> buf, "C=%d\n" % c
...
print >> f, buf.getvalue()
Take a look at "Literal String Interpolation" https://www.python.org/dev/peps/pep-0498/
I found it through the http://www.malemburg.com/
Python has a %
operator for this.
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
See this reference for all supported format specifiers.
You could as well use format:
>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge
Something like...
greetings = 'Hello {name}'.format(name = 'John')
Hello John
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=':')