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())) ③
with pattern, you safely open the file and let Python close it for you.
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.
-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.)
+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()))
⁂