PYTHON fprintf

is this article helpful?
Python replacement for PHP's fprintf [ edit | history ]
fp = open('date.txt', 'w')
fp.write("%04d-%02d-%02d" % (year, month, day))

outputs a newline (2.x):
fp = open('date.txt', 'w')
print >> fp, "%04d-%02d-%02d" % (year, month, day)

outputs a newline (3.x):
fp = open('date.txt', 'w')
print("%04d-%02d-%02d" % (year, month, day), file=fp)

PHP fprintf

PHP original manual for fprintf [ show | ]


(PHP 5)

fprintfWrite a formatted string to a stream


int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] )

Write a string produced according to format to the stream resource specified by handle .



A file system pointer resource that is typically created using fopen().


See sprintf() for a description of format .



Return Values

Returns the length of the string written.


Example #1 fprintf(): zero-padded integers

if (!($fp fopen('date.txt''w'))) {

// will write the formatted ISO date to date.txt

Example #2 fprintf(): formatting currency

if (!($fp fopen('currency.txt''w'))) {

$money1 68.75;
$money2 54.35;
$money $money1 $money2;
// echo $money will output "123.1";
$len fprintf($fp'%01.2f'$money);
// will write "123.10" to currency.txt

echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands