Ich habe mal eine Banale Frage in der ich im Netz einfach keine lösung
gefunden habe

Wie kann ich mit einer while schleife, in einer txt Datei immer
nur die Letzte zeile auslesen.
LG ST
Code: Alles auswählen
import os
def last_line(filename, chunk_size=80):
nl = os.linesep
with open(filename) as f:
while True:
f.seek(-(chunk_size), 2)
chunk = f.read()
if nl in chunk[:-1]:
return chunk.splitlines()[-1]
chunk_size *= 2
Code: Alles auswählen
def last_line(filename, chunk_size=80):
with open(filename) as f:
while True:
f.seek(-(chunk_size), 2)
lines = f.read().splitlines()
if len(lines) > 1:
return lines[-1]
chunk_size *= 2
Hallo ihr alleBlackJack hat geschrieben:@querdenker: IMHO keine guten Freunde, das skaliert nicht besonders gut mit der Dateigrösse.
@sttrader: Warum ``while``? Eine ``for``-Schleife über die Datei wäre einfacher.
Darum kommst du mit `os.linesep` ja auch nicht weitersnafu hat geschrieben:Ich dachte, Python würde inzwischen standardmäßig "universal newlines" aktivieren.
Ich hatte gedacht, dass dies auch das Verhalten für das Built-in `open` wäre. Getestet habe ich es unter Windows noch nicht. Und `newlines` steht bei `io.open` auf `None`. Aber gut, offenbar sind `io.open` und `open` etwas anderes, wenn man nach deiner Aussage geht.newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '', no translation takes place. If newline is any of the
other legal values, any '\n' characters written are translated to
the given string.
The [mod]io[/mod] module provides the Python interfaces to stream handling. The built-in open() function is defined in this module.