Reading file changes in Python 3 and Python 2

I tried to read a changing file in Python, where the script can handle newly added lines. I have a script below which lines are printed in a file and do not end.

with open('tmp.txt','r') as f: while True: for line in f: print(line.replace('\n','')) 

Where 'tmp.txt' consists of some lines, for example:

 a d 2 3 

If I am attached to the tmp.txt file, for example:

 echo "hi" >> tmp.txt 

the script will print a new line if the script is running with Python 3 but not with Python 2. Is there an equivalent in Python 2? And what is different between the two versions of Python in this case?

+6
source share
2 answers

Looking at f objects in python 2.7 vs 3.5, they are slightly different

Following

 with open('tmp.txt','r') as f: print(f) print(type(f)) 

In python 2.7 returns

 <open file 'tmp.txt', mode 'r' at 0x0000000003DD9780> <type 'file'> 

While in python 3.5 it returns

 <_io.TextIOWrapper name='tmp.txt' mode='r' encoding='cp1252'> <class '_io.TextIOWrapper'> 

The same behavior can be obtained in python 2.7 using

 import io with io.open('tmp.txt','r') as f: while True: for line in f: print(line.replace('\n','')) 
+5
source

That should do the trick.

 import time def follow(file): thefile.seek(0,2) while True: line = thefile.readline() if not line: time.sleep(0.1) continue yield line if __name__ == '__main__': logfile = open("log.txt","r") loglines = follow(logfile) for line in loglines: print(line) 

Found here: Reading from a frequently updated file.

+1
source

Source: https://habr.com/ru/post/1011917/


All Articles