Just when I was reviewing the code I wrote a long time ago
python
try:
with log_path.open(encoding='utf-8') as log_file:
for line in log_file.readlines():
...
I noticed that I was writing code like this here and there.
The file handle for Python (Note: version 2.4 and above) is an iterator, so in the above code
python
for line in log_file.readlines():
Line is
python
for line in log_file:
Should be written.
Also when combined with ʻenumerate ()`
python
for line_number, line in enumerate(log_file.readlines(), 1):
not,
python
for line_number, line in enumerate(log_file, 1):
There is no problem writing.
If for some reason you really want to read the file at once using the readlines ()
method, instead of writing readlines ()
in the for
statement,
python
log_lines = []
try:
with log_path.open(encoding='utf-8') as log_file:
log_lines = log_file.readlines()
except IOError:
pass
for line in log_lines:
...
I think it should be written like this.
Occasionally I see a lot of long code in the with
block, but I should close the opened file if I don't need it, and the with
block has no scope, so I can skip unnecessary processing without sloppy writing. That's right.
As mentioned above, I was quite confused about how bad my code was, so it was a tip I wrote with my own caution.
Recommended Posts