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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With