From 0e7af80ea5408e1252cf8eeca8af9d17daf7801a Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Sun, 16 Aug 2009 13:30:35 -0400 Subject: [PATCH] added right-justified format specifier; added note about Python 3.0 compatibility. --- files.html | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/files.html b/files.html index c67d5df..2703d8a 100644 --- a/files.html +++ b/files.html @@ -6,6 +6,7 @@ @@ -239,25 +240,38 @@ ValueError: I/O operation on closed file. with open('examples/favorite-people.txt', encoding='utf-8') as a_file: for a_line in a_file: line_number += 1 - print('{} {}'.format(line_number, a_line.rstrip())) + print('{:>4} {}'.format(line_number, a_line.rstrip()))
  1. Using the with pattern, you safely open the file and let Python close it for you.
  2. To read a file one line at a time, use a for loop. That’s it. Besides having explicit methods like read(), the stream object is also an iterator which spits out a single line every time you ask for a value. -
  3. Using the format() string method, you can print out the line number and the line itself. (The a_line variable contains the complete line, carriage returns and all. The rstrip() string method removes the trailing whitespace, including the carriage return characters.) +
  4. Using the format() string method, you can print out the line number and the line itself. The format specifier {:>4} means “print this argument right-justified within 4 spaces.” The a_line variable contains the complete line, carriage returns and all. The rstrip() string method removes the trailing whitespace, including the carriage return characters.
 you@localhost:~/diveintopython3$ python3 examples/oneline.py
-1 Dora
-2 Ethan
-3 Wesley
-4 John
-5 Anne
-6 Mike
-7 Chris
-8 Sarah
-9 Alex
-10 Lizzie
+ 1 Dora + 2 Ethan + 3 Wesley + 4 John + 5 Anne + 6 Mike + 7 Chris + 8 Sarah + 9 Alex + 10 Lizzie + +
+

Did you get this error? +

+you@localhost:~/diveintopython3$ python3 examples/oneline.py
+Traceback (most recent call last):
+  File "examples/oneline.py", line 4, in <module>
+    print('{:>4} {}'.format(line_number, a_line.rstrip()))
+ValueError: zero length field name in format
+

If so, you’re probably using Python 3.0. You should really upgrade to Python 3.1. +

Python 3.0 supported string formatting, but only with explicitly numbered format specifiers. Python 3.1 allows you to omit the argument indexes in your format specifiers. Here is the Python 3.0-compatible version for comparison: +

print('{0:>4} {1}'.format(line_number, a_line.rstrip()))
+