2017-03-29 44 views
0

我正在使用python和matplotlib从XY数据(〜1000文件夹和增长)的相当大的数据库生成绘图。每个文件夹都包含一个包含XY数据的CSV文件,我想要生成散点图。 由于更多数据文件夹被定期添加到根文件夹,我想定期运行我的脚本以保持绘图更新。不幸的是,这个脚本现在运行了大约10分钟,我预测它会持续运行时间越来越长。绘图生成:如果图已经存在,则停止for-loop

我想通过向代码添加一些东西来加速脚本,如果文件夹中存在.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') 

回答

0

所有你需要的是从英文你原来的问题翻译成Python:

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

您可以使用

import os 
os.path.isfile(fname) 

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

root + 'plot.png' 

必须在当前目录。如果你想摆脱你的for循环的使用关键字

break 
+0

确定这是非常明确的,它工作

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

: 可以因此添加到您,如果句子。感谢您指出了这一点! – skleijn

相关问题