for
loop through the lines of a downloaded text file
forURL.py
On pain of torture, from those bloody hands
Throw your mistempered weapons to the ground,
And hear the sentence of your movèd prince.
Things to try
-
We gave the
keyword
argument
end = ""
to
print
because each
s
already ends with a newline.
Without the
end = ""
,
the output would have been double-spaced.
Another way to avoid double-spacing is the following.
The
r
in
rstrip
stands for
“right”;
there’s also an
lstrip
.
for line in lines:
try:
s = line.decode("utf-8") #Convert sequence of bytes to string of characters.
except UnicodeError as error:
print(error, file = sys.stderr)
sys.exit(1)
s = s.rstrip() #Chop the trailing whitespace (including any newline) off of s.
print(s)
Want to make your code harder to read?
for line in lines:
print(line.decode("utf-8").rstrip())
See also the
newline
keyword argument of
open
.