diff --git a/files.html b/files.html index 864bb27..32252dd 100644 --- a/files.html +++ b/files.html @@ -106,36 +106,35 @@ UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 28: chara
# continued from the previous example ->>> a_file.read() ① +>>> a_file.read() ① '' ->>> a_file.seek(0) ② +>>> a_file.seek(0) ② 0 ->>> a_file.read(16) ③ +>>> a_file.read(16) ③ 'Dive Into Python' ->>> a_file.read(1) ④ +>>> a_file.read(1) ④ ' ' ->>> a_file.read(1) ⑤ +>>> a_file.read(1) '是' ->>> a_file.tell() ⑥ +>>> a_file.tell() ⑤ 20
read() method simply return an empty string.
+seek() method moves to a specific byte position in a file.
+read() method can take an optional parameter, the number of characters to read.
+FIXME
# continued from the previous example ->>> a_file.seek(17) ① +>>> a_file.seek(17) ① 17 ->>> a_file.read(1) ② +>>> a_file.read(1) ② '是' ->>> a_file.tell() ③ +>>> a_file.tell() ③ 20
A “line” of a text file is just what you think it is — you type a few words and press ENTER, and now you’re on a new line. A line of text is a sequence of characters delimited by… what exactly? Well, it’s complicated, because text files can use several different characters to mark the end of a line. Every operating system has its own convention. Some use a carriage return character, others use a line feed character, and some use both characters at the end of every line. + +
Now breathe a sigh of relief, because Python handles line endings automatically by default. If you say, “I want to read this text file one line at a time,” Python will figure out which kind of line ending the text file uses and and it will all Just Work. + +
++ +☞If you need fine-grained control over what’s considered a line ending, you can pass the optional
newlineparameter to theopen()function. See theopen()function documentation for all the gory details. +
So, how do you actually do it? Read a file one line at a time, that is. It’s so simple, it’s beautiful. + +
line_number = 0
+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())) ③
+FIXME -
FIXME what's a "line"? (line endings discussion, universal line endings, etc.) - - +
+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