Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the last line of a file in Python?

Tags:

I have a two requirements .

First Requirement-I want to read the last line of a file and assign the last value to a variable in python.

Second Requirement-

Here is my sample file.

<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/> <context:property-placeholder location="filename.txt"/> 

From this file I want to read the content i.e filename.txt which will be after <context:property-placeholder location= ..And want to assign that value to a variable in python.

like image 502
techi Avatar asked Sep 16 '17 21:09

techi


People also ask

How do I read the last line of a file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file. Try using tail to look at the last five lines of your .

How do you read the last few lines of a file in Python?

As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to read last N lines of a file using Python. In this approach, the idea is to use a negative iterator with the readlines() function to read all the lines requested by the user from the end of file.

How do you read a single line from a file in Python?

Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement.


1 Answers

A simple solution, which doesn't require storing the entire file in memory (e.g with file.readlines() or an equivalent construct):

with open('filename.txt') as f:     for line in f:         pass     last_line = line 

For large files it would be more efficient to seek to the end of the file, and move backwards to find a newline, e.g.:

import os  with open('filename.txt', 'rb') as f:     try:  # catch OSError in case of a one line file          f.seek(-2, os.SEEK_END)         while f.read(1) != b'\n':             f.seek(-2, os.SEEK_CUR)     except OSError:         f.seek(0)     last_line = f.readline().decode() 

Note that the file has to be opened in binary mode, otherwise, it will be impossible to seek from the end.

like image 82
Eugene Yarmash Avatar answered Oct 10 '22 02:10

Eugene Yarmash