Z
Z
Zellily2017-05-03 22:47:28
Python
Zellily, 2017-05-03 22:47:28

What is the best way to parse a file? Compare a string with a pattern or rely on a uniform file structure?

I am using for line in file. If the line contains the template I need, then the desired object is found, I will write it down in the structure field.
But there is an option to consider the file homogeneous. For example, I know that object A was found, which means that the next required object B will be found in three lines. You can just read three readline lines, and the fourth one will be just what I need. I'll write it down in the structure field.
Which way is better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2017-05-03
@dimonchik2013

well, the iterator will have to go through them anyway))
if the file is small, it's easier to read into the list and then list conprehention

X
x67, 2017-05-03
@x67

Depends on what the file is and how likely something is to go wrong. If this is a log of some program and 4 lines takes one action, where the time is written in the first line, the parameters are written in the second, the air humidity in the third, and the desired parameter in the fourth, then you can optimize. If this is a site that needs to be parsed and is actively updated, it is better to use the most universal methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question