Reputation: 35
I don't know is possible deleting previous line what the program saving in memory? In the file "Server.txt" I am looking for word: Server
but the file overwrites all the time and memory remember all of this line where line starting with "Server" (previous too). How I can delete or print only the line which is last?
Code:
filepath = 'server.txt'
with open(filepath) as fp:
for single_line in fp.readlines():
if single_line.startswith("Server"):
print(single_line)
Example "server.txt":
Accept-Ranges: bytes
ETag: "144-4e5a18dd96d87"
Server: Apache/2.4.6 (Unix) OpenSSL/1.0.1t PHP/5.5.3
Content-Length: 324
Content-Type: text/html
Date: Mon, 19 Mar 2018 21:03:03 GMT
Server: Apache/2.2.21 (Unix) mod_wsgi/3.3 Python/2.4.4 mod_ssl/2.2.21 OpenSSL/0.9.8k PHP/5.2.9
Content-Type: text/html; charset=utf-8
Date: Mon, 19 Mar 2018 21:03:06 GMT
Server: Apache/2.2.11 (Unix) PHP/5.2.9 mod_ssl/2.2.11 OpenSSL/0.9.8k mod_wsgi/3.3 Python/2.7.3
Content-Type: text/html; charset=iso-8859-1
Return is:
Server: Apache/2.2.21 (Unix) mod_wsgi/3.3 Python/2.4.4 mod_ssl/2.2.21 OpenSSL/0.9.8k PHP/5.2.9
Server: Apache/2.4.6 (Unix) OpenSSL/1.0.1t PHP/5.5.3
Server: Apache/2.2.11 (Unix) PHP/5.2.9 mod_ssl/2.2.11 OpenSSL/0.9.8k mod_wsgi/3.3 Python/2.7.3
How can I get these values one by one or like my subject, delete the previous one?
Upvotes: 1
Views: 276
Reputation: 403
If I understand your problem correctly, the file will continue to update with additional information appended to the end. So you only want the last instance of ‘Server’ to print. You need to store the newest instance into a variable and print the variable when the loop is complete. Since it will overwrite every time a new instance is found, it will only print the last instance.
filepath = 'temp.txt'
with open(filepath) as fp:
for single_line in fp.readlines():
if single_line.strip().startswith("Server"):
last_instance = single_line.strip()
print(last_instance)
I added ‘.strip()’ to the end because your text had blank spaces that was not correctly finding ‘Server’ at the beginning of the line.
If you want to keep the program running constantly and have it print the newest update, you’ll need to put the code in a loop, create a timer command, and add a clear command before every iteration.
Reference Clear screen in shell for additional information on clearing the previously printed information.
Upvotes: 1