Read Last Line of Text File

How to only read the last line from a text file

Use tail ;)

line=$(tail -n 1 input_file)
echo $line

Reading the 2 last line from a text

Since

 File.ReadAllLines("C:\\test.log");

returns an array you can take the last two items of the array:

 var data = File.ReadAllLines("C:\\test.log");

string last = data[data.Length - 1];
string lastButOne = data[data.Length - 2];

In general case with long files (and that's why ReadAllLines is a bad choice) you can implement

public static partial class EnumerableExtensions {
public static IEnumerable<T> Tail<T>(this IEnumerable<T> source, int count) {
if (null == source)
throw new ArgumentNullException("source");
else if (count < 0)
throw new ArgumentOutOfRangeException("count");
else if (0 == count)
yield break;

Queue<T> queue = new Queue<T>(count + 1);

foreach (var item in source) {
queue.Enqueue(item);

if (queue.Count > count)
queue.Dequeue();
}

foreach (var item in queue)
yield return item;
}
}

...

var lastTwolines = File
.ReadLines("C:\\test.log") // Not all lines
.Tail(2);

Read two lines before last line of text file

Maybe you could use this extension method:

public static class EnumerableExtensions
{
public static T GetLastItem<T>(this IEnumerable<T> seq, int countFromEnd)
{
if(seq is IList<T> list) return list[^countFromEnd];
using var enumerator = seq.Reverse().GetEnumerator();
while(enumerator.MoveNext())
{
if(--countFromEnd == 0) return enumerator.Current;
}
throw new ArgumentOutOfRangeException();
}
}

Usage:

var secondLastLine = File.ReadLines("SomeFile.log").GetLastItem(2);

If you don't use C#8, so you can't use Ranges, replace return list[^countFromEnd] with return list[list.Count - countFromEnd].

Extract only the last line using read() function

Perhaps:

list.txt:

sdfs
sdfs
fg34
345
gn
4564

Hence:

with open('list.txt') as fileObj:
print(list(fileObj)[-1])

Using pathlib:

from pathlib import Path
print(Path('list.txt').read_text().splitlines()[-1])

OUTPUT:

4564

How to read the last line of a text file into a variable using Bash?

tag=$( tail -n 1 history.txt )

Print Last Line of File Read In with Python

One option is to use file.readlines():

f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()

If you don't need the file after, though, it is recommended to use contexts using with, so that the file is automatically closed after:

with open(inputFile, "r") as f1:
last_line = f1.readlines()[-1]


Related Topics



Leave a reply



Submit