【问题标题】:Plot generation: stop for-loop if plot already exists绘图生成:如果绘图已经存在,则停止 for-loop
【发布时间】:2017-03-29 21:10:50
【问题描述】:

我正在使用 python 和 matplotlib 从相当大的 XY 数据数据库(约 1000 个文件夹并且还在增长)生成绘图。每个文件夹都包含一个 CSV 文件,其中包含我要生成散点图的 XY 数据。 由于会定期将更多数据文件夹添加到根文件夹中,因此我想定期运行我的脚本以保持绘图更新。不幸的是,这个脚本现在运行了大约 10 分钟,我预见它会运行得越来越长。

如果文件夹中存在 .png 文件,我想通过在我的代码中添加一些内容来加快脚本速度,这样会跳过在当前文件夹中搜索 XY 数据。我应该对下面的代码进行哪些修改以反映这一点?

import os
import matplotlib.pyplot as plt

# Find files containing XY data
for root, dirs, files in os.walk('D:/temp\\', topdown=False):
    for name in files:
       #find and check txt file
        if name.startswith('XY') and name.endswith('.txt'):
            # read data and store lines in list
            try:
                posX = list() #list of x-positions
                posY = list() #list of y-positions
                filepath = os.path.join(root, name) 
                fp = open(filepath)
                for line in fp:
                    # make lists from the csv rows
                    content = line.split()
                    posX.append(float(content[0]))
                    posY.append(float(content[1]))                    
                fp.close()
                # prepare a scatter plot
                figure = plt.scatter(posX,posY)
                # save plot as png       
                plt.savefig(root+'plot.png')
                # clear plot data for next for loop iteration
                plt.clf()

更新: 使用下面的答案,我更新了第二个 for 循环中的 if 语句:

#find and check txt file
    if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root+'plot.png'):
(...)
    else:
        print('no new data available')

【问题讨论】:

    标签: python python-2.7 matplotlib plot


    【解决方案1】:

    您只需将原始问题从英语翻译成 Python:

    if name.startswith('XY') and name.endswith('.txt') \
       and not os.path.isfile(root+'plot.png'): ...
    

    【讨论】:

      【解决方案2】:

      你可以使用

      import os
      os.path.isfile(fname)
      

      如果你的情节存在,你就知道有一个名为

      的文件
      root + 'plot.png'
      

      必须在您的当前目录中。 因此,您可以将其添加到您的 if 句中:

      if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root + 'plot.png'):
      

      如果您想跳出 for 循环,请使用关键字

      break
      

      【讨论】:

      • 好的,这很清楚,而且有效。感谢您指出这一点!
      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 2019-08-22
      相关资源
      最近更新 更多