This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

Many people sometimes only need to get a fixed line in the article, so I know this line, HOW do I need to get, this share, will take you to see how to achieve.

   

You might say read this line, if I read this line at the beginning of something, if I want to get the corresponding line, can I just read it? And the answer is yes.
There’s another way, I know where the file is. Knowing the number of rows I’m going to take, I can just take it out in Python. It’s what line I want, and I just tell the code, you read me the line.
We have prepared the beijing.txt file for our demo.
The specific contents of the text are as follows:

   

beijing
shanghai
tianjin
Copy the code
So I’m going to get the first line of text, and how my code is going to do that, so let’s see how we’re going to do that in our code.
import linecache
with open('beijing.txt',encoding='utf-8') as f:    
    print(linecache.getline(f,1))
Copy the code
First of all, we’re going to open the file, and then we’re going to need the getline

Running result:

To facilitate our subsequent calls, we can do a little further encapsulation
import linecache
class GetTextLine(object) :
    def __init__(self,filepath:str,line:int) :
        self.filepath=filepath
        self.line=line
    def readline(self) - >str:
        with open(self.filepath, encoding='utf-8') as f:
            return (linecache.getline(f, 1))
Copy the code

Made a simple encapsulation, we will use in the future when the simpler. We can think of these general method, the encapsulated between in our follow-up development process can be rapid development, we can put all our accumulation of generic methods to do a lot of summary, and then placed in a separate module, in the subsequent use, we can directly to call, reduce the development workload our code.