在Python 3和Python 2中阅读更改文件

Jia*_*Gao 6 python file

我试图在Python中读取一个更改的文件,脚本可以处理新添加的行.我有下面的脚本打印出文件中的行,但不会终止.

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

其中'tmp.txt'由一些行组成,例如:

a
d
2
3
Run Code Online (Sandbox Code Playgroud)

如果我附加到'tmp.txt'文件,例如使用:

echo "hi" >> tmp.txt
Run Code Online (Sandbox Code Playgroud)

如果脚本使用Python 3运行,脚本将打印出新行,而不是Python 2.在Python 2中是否存在等效脚本?在这种情况下,两个版本的Python有什么不同?

mgi*_*ert 5

看一下fpython 2.7 vs 3.5 中的对象,它们略有不同

下列

with open('tmp.txt','r') as f:
    print(f)
    print(type(f))
Run Code Online (Sandbox Code Playgroud)

在python 2.7中返回

<open file 'tmp.txt', mode 'r' at 0x0000000003DD9780>
<type 'file'>
Run Code Online (Sandbox Code Playgroud)

而在python 3.5中返回

<_io.TextIOWrapper name='tmp.txt' mode='r' encoding='cp1252'>
<class '_io.TextIOWrapper'>
Run Code Online (Sandbox Code Playgroud)

在python 2.7中可以获得相同的行为

import io

with io.open('tmp.txt','r') as f:
    while True:
        for line in f:
            print(line.replace('\n',''))
Run Code Online (Sandbox Code Playgroud)