Don't use readlines () in your Python for statement!

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

Don't use readlines () in your Python for statement!
Don't use \ d in Python 3 regular expressions!
Use pathlib in Maya (Python 2.7) for upcoming Python 3.7
[Introduction to Python] How to use the in operator in a for statement?
Use config.ini in Python
Python basics ② for statement
Use dates in Python
Use Valgrind in Python
Use Python in your environment from Win Automation
Use profiler in Python
python: Use your own class for numpy ndarray
[Python] for statement error
[For beginners] How to use say command in python!
Create your own Big Data in Python for validation
Use the CASA Toolkit in your own Python environment
Convenient to use matplotlib subplots in a for statement
Python list, for statement, dictionary
Use let expression in Python
Use Measurement Protocol in Python
Use callback function in Python
Use parameter store in Python
Use HTTP cache in Python
Search for strings in Python
Use MongoDB ODM in Python
Use list-keyed dict in Python
Techniques for sorting in Python
Use Random Forest in Python
Don't make test.py in Python!
Use Spyder in Python IDE
[Python / PyQ] 4. list, for statement
About "for _ in range ():" in python
How to define multiple variables in a python for statement
[Road to intermediate Python] Use if statement in list comprehension
I didn't know how to use the [python] for statement
Check for memory leaks in Python
[Python] logging in your own module
Python Exercise for Beginners # 2 [for Statement / While Statement]
Use fabric as is in python (fabric3)
How to use SQLite in Python
Next, use Python (Flask) for Heroku!
Use rospy with virtualenv in Python3
Python for statement ~ What is iterable ~
How to use Mysql in python
Use Python in pyenv with NeoVim
How to use ChemSpider in Python
How to use PubChem in Python
Beginners use Python for web scraping (1)
Use OpenCV with Python 3 in Window
Run unittests in Python (for beginners)
[Python] Multiplication table using for statement
Beginners use Python for web scraping (4) ―― 1
Wrap (part of) the AtCoder Library in Cython for use in Python
Install Networkx in Python 3.7 environment for use in malware data science books
A memo for those who use Python in Visual Studio (me)
[Introduction to Python] How to use class in Python?
Use print in a Python2 lambda expression
Create your own Linux commands in Python
Use DeepL with python (for dissertation translation)
[LLDB] Create your own command in Python
Notes on nfc.ContactlessFrontend () for nfcpy in python
Inject is recommended for DDD in Python