在Python 3和Python 2中读取更改文件 [英] Reading changing file in Python 3 and Python 2

查看:99
本文介绍了在Python 3和Python 2中读取更改文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Python读取一个不断变化的文件,脚本可以在其中处理新添加的行.我有下面的脚本,该脚本可以打印出文件中的行,并且不会终止.

I was trying to read a changing file in Python, where a script can process newly appended lines. I have the script below which prints out the lines in a file and does not terminate.

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

"tmp.txt"由几行组成,例如:

Where 'tmp.txt' consists of some lines, e.g.:

a
d
2
3

如果我将其附加到"tmp.txt"文件中,例如使用:

If I appended to the 'tmp.txt' file, such as using:

echo "hi" >> tmp.txt

如果脚本是使用Python 3而不是Python 2运行的,则该脚本将打印出新行.在这种情况下,两个版本的Python有何不同?

The script will print out the new line in if the script is run with Python 3, but not with Python 2. Is there an equivalent in Python 2? And what's different between the two versions of Python in this case?

推荐答案

查看python 2.7与3.5中的对象 f 略有不同

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

以下

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

在python 2.7中返回

In python 2.7 returns

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

在python 3.5中返回

Whereas in python 3.5 returns

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

相同的行为可以在python 2.7中使用

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',''))

这篇关于在Python 3和Python 2中读取更改文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆