【问题标题】:Reading changing file in Python 3 and Python 2在 Python 3 和 Python 2 中读取更改文件
【发布时间】:2017-03-14 20:41:27
【问题描述】:

我试图在 Python 中读取一个更改文件,其中脚本可以处理新附加的行。我有下面的脚本,它打印出文件中的行并且不会终止。

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

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

a
d
2
3

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

echo "hi" >> tmp.txt

如果脚本在 Python 3 上运行,但在 Python 2 上不运行,脚本将打印出新行。在 Python 2 中是否有等价物?在这种情况下,两个版本的 Python 有什么不同?

【问题讨论】:

    标签: python file


    【解决方案1】:

    查看 python 2.7 和 3.5 中的对象 f,它们略有不同

    以下

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

    在 python 2.7 中返回

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

    而在 python 3.5 中返回

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

    在 python 2.7 中使用

    可以获得相同的行为
    import io
    
    with io.open('tmp.txt','r') as f:
        while True:
            for line in f:
                print(line.replace('\n',''))
    

    【讨论】:

      【解决方案2】:

      这应该可以解决问题。

      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)
      

      在这里找到原文:Reading from a frequently updated file

      【讨论】:

      • 重点是,通过我的方式,它与特定的计时器是异步的。如果您正在运行服务器或其他东西,这将是一个很大的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2015-05-09
      • 2014-07-29
      • 2018-09-06
      • 2023-01-25
      • 2011-07-08
      相关资源
      最近更新 更多