【问题标题】:How to stop printing if the value is the same than the previous one in a while cycle如果值与循环中的前一个值相同,如何停止打印
【发布时间】:2017-11-23 09:23:36
【问题描述】:

以下代码将显示文件夹中创建的最新文件的名称及其内容,并且还将保持每 30 秒打印一次。

import glob    
import os      
import time

while True: 

 newest=max(glob.iglob('/Users/BetaBrawler/Downloads/HernanVillela/*'), key=os.path.getctime)

 print newest     
 file = open(newest,'r')     
 texto = [x.strip() for x in file.readlines()]

 print texto     
 time.sleep(30)

我唯一想做的是,如果以下输出与前一个输出具有相同的值(相同的文件及其内容),控制台将停止打印,并且仅在文件夹中创建新文件时才打印。

【问题讨论】:

    标签: python file printing while-loop cycle


    【解决方案1】:
    import glob    
    import os      
    import time
    
    current = None
    
    while True: 
       newest = max(glob.iglob('/Users/BetaBrawler/Downloads/HernanVillela/*'), key=os.path.getctime)
    
       if newest != current:
           current = newest
           print newest     
           with open(newest, 'r') as file_:
               texto = [x.strip() for x in file_.readlines()]
               print texto
    
       time.sleep(30)
    

    【讨论】:

      【解决方案2】:
      import glob
      import os
      import time
      
      oldfile = None
      while True:
          newest = max(glob.glob('/Users/BetaBrawler/Downloads/HernanVillela/*'), key=os.path.getctime)
      
          if newest == oldfile:
              time.sleep(30)
              continue
      
          oldfile = newest
          with open(newest) as infile:
              print [line.strip() for line in infile]
          time.sleep(30)
      

      【讨论】:

      • 这个重构改变了原始脚本的几个行为: 1. 如果文件没有改变,它不会休眠 30 秒。效果是在文件没有变化的情况下,内容会很快打印出来,直到找到一个新文件。 2.文件的每一行将不再是stripped。 3. 我认为newest = oldfile 应该是newest == oldfile 才能正常工作。
      • @theunraveler:感谢您的错误报告。我想我有一个休息日。我已经把它们都修好了,现在
      • @theunraveler 代码运行良好,但它只打印最后创建的文件的内容。我应该添加或删除一些东西来打印文件名吗?
      • @Beta: print newest 会这样做
      猜你喜欢
      • 2022-12-14
      • 1970-01-01
      • 2022-12-05
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多